如何使用grep在循环中搜索字符串

时间:2019-04-14 18:16:57

标签: r

我有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)

2 个答案:

答案 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