Replace NA in column with value in adjacent column

You have to do

TEST$UNIT[is.na(TEST$UNIT)] <- TEST$STATUS[is.na(TEST$UNIT)]

so that the value will be replaced with the adjacent value. Otherwise there is a mismatch between the number of values to be replaced and the values to replace them with. This would result in the values being replaced in row order. It works in this case because the two values being replaced are the first two.


TEST$UNIT = ifelse(is.na(TEST$UNIT), paste(TEST$STATUS),paste(TEST$UNIT));TEST
       UNIT   STATUS TERMINATED      START       STOP
1    ACTIVE   ACTIVE 1999-07-06 2007-04-23 2008-12-05
2  INACTIVE INACTIVE 2008-12-05 2008-12-06 4712-12-31
3       200   ACTIVE 2000-08-18 2004-06-01 2007-01-31
4       200   ACTIVE 2000-08-18 2007-02-01 2008-04-18
5       200 INACTIVE 2000-08-18 2008-04-19 2010-11-28
6       200   ACTIVE 2008-08-18 2010-11-29 2010-12-29
7       200 INACTIVE 2008-08-18 2010-12-30 4712-12-31
8       300   ACTIVE 2006-09-19 2007-10-29 2008-02-04
9       300   ACTIVE 2006-09-19 2008-02-05 2008-06-29
10      300   ACTIVE 2006-09-19 2008-06-30 2009-02-06
11      300 INACTIVE 1999-03-15 2009-02-07 4712-12-31

It didn't work because status was a factor. When you mix factor with numeric then numeric is the least restrictive. By forcing status to be character you get the results you're after and the column is now a character vector:

TEST$UNIT[is.na(TEST$UNIT)] <- as.character(TEST$STATUS[is.na(TEST$UNIT)])

##        UNIT   STATUS TERMINATED      START       STOP
## 1    ACTIVE   ACTIVE 1999-07-06 2007-04-23 2008-12-05
## 2  INACTIVE INACTIVE 2008-12-05 2008-12-06 4712-12-31
## 3       200   ACTIVE 2000-08-18 2004-06-01 2007-01-31
## 4       200   ACTIVE 2000-08-18 2007-02-01 2008-04-18
## 5       200 INACTIVE 2000-08-18 2008-04-19 2010-11-28
## 6       200   ACTIVE 2008-08-18 2010-11-29 2010-12-29
## 7       200 INACTIVE 2008-08-18 2010-12-30 4712-12-31
## 8       300   ACTIVE 2006-09-19 2007-10-29 2008-02-04
## 9       300   ACTIVE 2006-09-19 2008-02-05 2008-06-29
## 10      300   ACTIVE 2006-09-19 2008-06-30 2009-02-06
## 11      300 INACTIVE 1999-03-15 2009-02-07 4712-12-31