数据表两列中的公共条目

时间:2018-12-25 19:47:07

标签: r data.table

我有两个具有以下内容的数据表

library('data.table')
df = data.table('rank' = c(1,2,3,4,5,6,7,8,9,10), 'h1' =c ('eye', 'arm', 'elbow', 'leg', 'nose', 'ear', 'nose' ,'hand' ,'hair', 'finger'), 'h2' = c( 'arm', 'fear', 'mouth', 'nose', 'back', 'bone' ,'hand' ,'hair', 'tail', 'nail'))
    rank     h1    h2
1:    1    eye   arm
2:    2    arm  fear
3:    3  elbow mouth
4:    4    leg  nose
5:    5     no  back
6:    6    ear  bone
7:    7   nose  hand
8:    8   hand  hair
9:    9   hair  tail
10:   10 finger  nail
df2 = data.table ('aa' = c('arm', 'leg', 'hair'), 'group' = c('up', 'down', 'up'))
   aa group
1:  arm    up
2:  leg  down
3:  hair   up

我需要找到df1中两列之间的公共条目。那很容易做到,我明白了。 df2显示与df1中的条目相对应的组。 我需要按照组在df1中找到常用条目 将会是

  

手臂,头发(向上)

     

腿(向下)

预期输出为

  

[false,true,false,false,false,false,false,false,true,false]

     

[false,false,false,true,false,false,false,false,false,false]

1 个答案:

答案 0 :(得分:1)

您没有确切说出您想要的输出,但是假设您要为group的所有值获取一个将aa列与h1匹配的布尔向量,则可以使用类似的命令(为清晰起见,请使用lapply) :

# join the 2 tables so we can access the 'group' column
df3 <- df2[df, on=c(aa="h1")]
# for all unique (and non NA) values of 'group', test if each row is of that group
lapply(df3[!is.na(group),unique(group)], function(x) df3[,!is.na(group) & group==x])

返回

[[1]]
 [1] FALSE  TRUE FALSE FALSE FALSE FALSE FALSE FALSE  TRUE FALSE

[[2]]
 [1] FALSE FALSE FALSE  TRUE FALSE FALSE FALSE FALSE FALSE FALSE

编辑:要添加相应的组名,请像这样使用names

results <- lapply(df3[!is.na(group),unique(group)], function(x) df3[,!is.na(group) & group==x])
# set the names of the list items to the group names
names(results) <- df3[!is.na(group),unique(group)]

我还在上面的代码中添加了注释。