replacing values in a column with another column R

后端 未结 4 1358
滥情空心
滥情空心 2020-11-30 10:47

I have two tables in different dimensions, now I want to replace value datA$swl1 with values in datB$swl2 according to userids.

datA

 id swl1
 1            


        
4条回答
  •  长情又很酷
    2020-11-30 11:09

    You can use merge to match by id, then replace in column swl1 those items from datB which exist:

    datC <- merge(datA, datB, all.x=TRUE)
    datC
    ##   id swl1 swl2
    ## 1  1  0.8  0.8
    ## 2  2  0.7   NA
    ## 3  3  0.4  0.6
    ## 4  4  0.7   NA
    ## 5  5  0.0  0.7
    

    This matches up the rows. Now to replace those values in column swl1 with the non-NA values from column swl2:

    datC$swl1 <- ifelse(is.na(datC$swl2), datC$swl1, datC$swl2)
    datC$swl2 <- NULL
    datC
    ##   id swl1
    ## 1  1  0.8
    ## 2  2  0.7
    ## 3  3  0.6
    ## 4  4  0.7
    ## 5  5  0.7
    

提交回复
热议问题