Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/74.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
如何使用grep在循环中搜索字符串_R - Fatal编程技术网

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

如何使用grep在循环中搜索字符串,r,R,我有两个数据帧 #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中,只有一个变量是sting。我试图使用grep获取df2的每个元素,

我有两个数据帧

 #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中,只有一个变量是sting。我试图使用grep获取df2的每个元素,在df1中找到相应的匹配项,并输出这些匹配项在df1中的位置的行位置向量。所以输出看起来像[1]12100

   I tired the following, but for some reason I get the following  
   result: 
整数(0)

我将非常感谢你的帮助

 result = NULL
 for (i in 1:nrow(df2)) {
 result = grep(df2[,1], df1)
 }
 print(result)
或者:

 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"))
结果或者:

 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"))
result遵循您的循环:

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
使用
字符
向量:

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
遵循您的循环:

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
使用
字符
向量:

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

这行吗
result=NULL for(i in 1:nrow(df2)){result=grep(df2[i,1],df1)}print(result)
是否有错误,或者只是
integer(0)
?@NelsonGon当我使用grep逐项搜索时,我找到了正确的匹配项和行位置。但是当我尝试循环时,输出是不正确的。使用循环的动机是我有很多项目要搜索,手动搜索效率很低。我想你需要
匹配
设置.seed(42);x@NelsonGon如果我合并,我需要确保匹配的项目彼此并排结束。但我仍然需要合并后匹配行的确切位置的输出。我尝试了各种合并命令,但都没能完成任务。这样行吗
result=NULL for(i in 1:nrow(df2)){result=grep(df2[i,1],df1)}print(result)
是否有错误,或者只是
integer(0)
?@NelsonGon当我使用grep逐项搜索时,我找到了正确的匹配项和行位置。但是当我尝试循环时,输出是不正确的。使用循环的动机是我有很多项目要搜索,手动搜索效率很低。我想你需要
匹配
设置.seed(42);x@NelsonGon如果我合并,我需要确保匹配的项目彼此并排结束。但我仍然需要合并后匹配行的确切位置的输出。我尝试了各种合并命令,但未能完成任务。