Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/73.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 基于大小不等的数据帧中的匹配行创建因子_R - Fatal编程技术网

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

R 基于大小不等的数据帧中的匹配行创建因子,r,R,我有两个数据帧 DF1 10 11 12 13 15 16 17 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的方法中。非常感谢您的帮助。我们可以使用%中的%创建一个逻辑向量,该向量可以通过as.

我有两个数据帧

DF1   
10
11
12
13
15
16
17
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的方法中。非常感谢您的帮助。

我们可以使用%中的
%创建一个逻辑向量,该向量可以通过
as.integer强制为二进制

DF3 <- DF1
DF3$newCol <- as.integer(DF3[,1] %in% DF2[,1])
DF3$newCol
#[1] 0 0 1 0 0 1 0 1

我们可以使用%
中的
%创建一个逻辑向量,它可以通过
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 <- 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

df3这对于
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

df3如果这是一个数据帧,那么它应该有一个列名。使用
DF1
是不够的。请尝试使用
as.integer(DF1[,1]%在%DF2[,1])
也许
DF3@akrun谢谢!它成功了,你能给我一个答案让我投赞成票吗?:)@谢谢,我将我的评论作为解决方案发布。如果这是一个数据框,那么它应该有一个列名。使用
DF1
是不够的。请尝试使用
as.integer(DF1[,1]%在%DF2[,1])
也许
DF3@akrun谢谢!它成功了,你能给我一个答案让我投赞成票吗?:)@ooh谢谢,我将我的评论作为解决方案发布。是否可以在“DF3$newCol”中为每个匹配行分配连续数字而不是1?请尝试
DF3$newCol[DF3$newCol!=0]抱歉,是否可以在“DF3$newCol”中为每个匹配行分配连续数字而不是1?请尝试
DF3$newCol[DF3$newCol!=0]
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