基于匹配来自不等大小的数据帧的行来创建因子

时间:2016-11-23 15:36:32

标签: r

我有两个数据帧

DF1   
10
11
12
13
15
16
17
19

DF2
    12
    16
    19

我正在寻找一种获得输出的方法

DF3
    10 0
    11 0
    12 1
    13 0
    15 0
    16 1
    17 0
    19 1

我知道如何从两个数据框中找到匹配的行

match = which(DF1 %in% DF2)

但丢失了找​​到为这两个数据帧中的匹配行分配0/1的方法。任何帮助都非常感谢。

2 个答案:

答案 0 :(得分:0)

我们可以使用%in%创建一个逻辑向量,可以使用as.integer

强制转换为二进制
DF3 <- DF1
DF3$newCol <- as.integer(DF3[,1] %in% DF2[,1])
DF3$newCol
#[1] 0 0 1 0 0 1 0 1

如果我们需要上述结果中的连续数字

DF3$newCol[DF3$newCol!=0] <- seq_along(DF3$newCol[DF3$newCol!=0])
DF3$newCol
#[1] 0 0 1 0 0 2 0 3

或另一种选择是

cumsum(DF1[,1] %in% DF2[,1])*(DF1[,1] %in% DF2[,1])
#[1] 0 0 1 0 0 2 0 3

答案 1 :(得分:0)

match这是一个很好的工作:

df3 <- df1
df3$matchCol <- +!is.na(match(df1[,1], df2[,1]))

#  df1 matchCol
#1  10        0
#2  11        0
#3  12        1
#4  13        0
#5  15        0
#6  16        1
#7  17        0
#8  19        1