我有2个数据帧。
#df1 dimensions [100,1]
item
"Like to cook"
"Enjoy football"
.............
"Love to run"
#df2 dimensions [3,1]
item
"Like to cook"
"Enjoy football"
"Love to run"
在df1和df2中,单个变量是字符串。我正在尝试使用grep来获取df2的每个元素,在df1中找到各自的匹配项,并输出这些匹配项在df1中的行位置的向量。所以输出看起来像[1] 1 2 100
I tired the following, but for some reason I get the following
result:
Integer(0)
。
谢谢您的帮助。
result = NULL
for (i in 1:nrow(df2)) {
result = grep(df2[,1], df1)
}
print(result)
答案 0 :(得分:1)
或者:
result <- which(df1$a %in% df2$a)
df1 <- data.frame(a = c("Like to cook", "Enjoy football", rep("any", 97),"Love to run"))
df2 <- data.frame(a = c("Like to cook", "Enjoy football", "Love to run"))
答案 1 :(得分:1)
跟随循环:
result = df
for (i in 1:nrow(df2)) {
result[i,] = grep(df2[i,], df[,1])
}
result
item
1 1
2 2
3 4
4 Love to run
使用character
向量:
result = character()
for (i in 1:nrow(df2)) {
result[i] = grep(df2[i,], df[,1])
}
result
无循环:
match(df2$item,df$item)
[1] 1 2 4