Replace NAs in one variable with values from another variable

前端 未结 4 1161
终归单人心
终归单人心 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 18:57

    Here is another approach though I like the transform:

    ##  dat <- read.table(text="VAR1    VAR2
    ##   1        NA
    ##   3        NA
    ##   NA       1 
    ##   NA       3
    ##   2        NA
    
    
    dat$VAR3 <- dat[, "VAR1"]
    dat[is.na(dat[, "VAR3"]), "VAR3"] <- dat[is.na(dat[, "VAR3"]), "VAR2"]
    dat
    ##   VAR1. VAR2. VAR3
    ## 1     1    NA    1
    ## 2     3    NA    3
    ## 3    NA     1    1
    ## 4    NA     3    3
    ## 5     2    NA    2
    ## 6    NA     1    1
    

提交回复
热议问题