Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.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_String - Fatal编程技术网

R 在具有字符串向量的数据帧中查找字符串

R 在具有字符串向量的数据帧中查找字符串,r,string,R,String,晚上好, 我有以下数据帧: df <- data.frame(I(list(c("nugget de blé","boeuf"),"nugget de blé"))) list_dishes <- c("nugget de blé") df如果您不介意使用tidyverse软件包,这里有一个解决方案: library(tidyverse) # I added a name to the column

晚上好,

我有以下数据帧:

df <- data.frame(I(list(c("nugget de blé","boeuf"),"nugget de blé")))
list_dishes <- c("nugget de blé")

df如果您不介意使用
tidyverse
软件包,这里有一个解决方案:

library(tidyverse)

# I added a name to the column of your data.frame
df <- data.frame(a = I(list(c("nugget de blé","boeuf"), 
                            "nugget de blé")))
list_dishes <- c("nugget de blé")

tibble(df) %>%
  mutate(id = row_number()) %>%
  rowwise() %>%
  mutate(found_dishes = map(a, ~str_detect(.x, list_dishes))) %>%
  unnest(found_dishes) %>%
  filter(found_dishes == T)

#> A tibble: 2 x 3
#> a            id found_dishes
#> <I<list>> <int> <lgl>       
#>1  <chr [2]>   1 TRUE        
#>2  <chr [1]>   2 TRUE    

库(tidyverse)
#我在data.frame的列中添加了一个名称
df%
行()
变异(找到的盘子=映射(a,~str探测(.x,列出盘子))%>%
unnest(找到的菜肴)%>%
过滤器(找到的_盘==T)
#>一个tibble:2x3
#>我找到了你的盘子
#>          
#>11正确
#>2正确

然后计算行数以查找找到的匹配项。

我们可以使用
sapply
grepl
base R

df$found_dishes <- sapply(df[[1]], function(x) any(grepl(list_dishes, x)))

df$found\u欢迎来到SO!考虑到您发布的数据,您希望的输出结果是什么?您的消息是什么。在这两种情况下,“布雷金块”都存在。因此,我期望以下输出:结果谢谢您的消息,这是一个解决方案,但是您知道是否可以从原始数据帧工作吗?并且不使用tidyverse进行转换。否则,根据您的建议,如果这是真的,我如何获得数据帧为1,如果是假的,如何获得数据帧为0。将mutate find_disks for
mutate(find_disks=map(a,~if_else(str_detect(.x,list_disks),1,0))
,,然后相应地更改
filter
行。感谢您的帮助Joao。非常感谢这是解决方案=)@pierrechiaverina在这种情况下,您可以使用嵌套的lapply,即
df[multiplecolumnsvec]谢谢,但此函数会将每个盘替换为true或false,例如字符串(“nugget de blé”、“boeuf”)的“true”、“false”)而如果两道菜之间至少有一个是真的,我想要真的。你有得到这个结果的窍门吗?Thanks@pierrechiaverina我使用了
any
来检查是否有任何正确/错误。再次感谢您的帮助
df$found_dishes <- sapply(df[[1]], function(x) any(grepl(list_dishes, x)))