Replace NAs in one variable with values from another variable

前端 未结 4 993
终归单人心
终归单人心 2020-12-10 18:25

How can I replace the \"NAs\" of a variable VAR1 with with the values of the second variable VAR2 to create a third variable VAR3 in R? The data looks like this:

<         


        
4条回答
  •  囚心锁ツ
    2020-12-10 19:00

    One way is to use ifelse:

    DF <- transform(DF, VAR3 = ifelse(!is.na(VAR1), VAR1, VAR2))
    

    where transform was used to avoid typing DF$ over and over, but maybe you will prefer:

    DF$VAR3 <- ifelse(!is.na(DF$VAR1), DF$VAR1, DF$VAR2)
    

提交回复
热议问题