replacing values in a column with another column R

后端 未结 4 1360
滥情空心
滥情空心 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:16

    You can obtain this result with one line of code:

    datA$swl1[datA$id %in% datB$id] <- datB$swl2
    #> datA
    #  id swl1
    #1  1  0.8
    #2  2  0.7
    #3  3  0.6
    #4  4  0.7
    #5  5  0.7
    

    With the %in% operator we select the entries of the column datA$swl1 that belong to rows with the same id as those listed in datB. These values in the column of datA$swl1 are then replaced with the entries of the swl2 column of datB.

提交回复
热议问题