根据其他数据行中的行选择行

时间:2019-05-03 21:51:44

标签: r dataframe

我有以下这些data.frames:

dt1

Id  Mother Weight  
1    elly     10
2    bina     20
3    sirce    30
4    tina     30
5    lina     40

dt2

Id   Mother  Weight  sex  
1    elly     10      M
2    bina     20      F
3    sirce    30      F

我想以这种方式从基于DT2(ID)的DT1(ID)中选择行:

new.dt

Id   Mother  Weight  sex
4    tina     30     NA
5    lina     40     NA

2 个答案:

答案 0 :(得分:1)

这是int rowCount = 10; int colCount = 10; Random rnd = new Random(); int[,] values = new int[rowCount, colCount]; for(int row = 0; row < rowCount; row++) for (int col = 0; col < colCount; col++) values[row, col] = rnd.Next(0, 100);

的一个选项
anti_join

数据

library(dplyr)
anti_join(dt1 %>% 
           mutate(sex = NA), dt2, by = 'Id')
#   Id Mother Weight sex
#1  4   tina     30  NA
#2  5   lina     40  NA

答案 1 :(得分:1)

transform(dt1[!dt1$Id %in% dt2$Id,], sex = NA)
#  Id Mother Weight sex
#4  4   tina     30  NA
#5  5   lina     40  NA

d = merge(dt1, dt2, all = TRUE)
d[is.na(d$sex),]
#  Id Mother Weight  sex
#4  4   tina     30 <NA>
#5  5   lina     40 <NA>