【发布时间】:2020-12-05 14:02:20
【问题描述】:
我正在尝试找出使用 dplyr 的语法,但遇到了如何将多个列传递给另一个函数(例如 str_detect)的问题。我想搜索一个小标题并选择检测到某个字符串的所有行。我可以针对特定列(例如下面示例中的 col3)运行它,但想查看一些和/或所有列。
library(dplyr)
library(stringr)
col1 <- c("plate_ABC", "text", "text", "text")
col2 <- c("text", "this is plate B", "text", "text")
col3 <- c("text", "text", "C-plate", "text")
df <- as_tibble(data_frame(col1, col2, col3))
df %>% filter(str_detect(col3, "plate"))
输出:
df %>% filter(str_detect(col3, "plate"))
## A tibble: 1 x 3
# col1 col2 col3
# <chr> <chr> <chr>
#1 text text C-plate
期望的输出:
df %>% filter(str_detect(?SOME/ALL Cols?, "plate"))
## A tibble: 3 x 3
# col1 col2 col3
# <chr> <chr> <chr>
#1 plate_ABC text text
#2 text this is plate B text
#3 text text C-plate
【问题讨论】:
-
您的预期解决方案是否不应使用
filter或reduce?我很困惑 -
不,如果我不清楚,抱歉。任何和所有的解决方案都很棒。我对编码非常陌生(只有几周的时间),所以我需要一段时间来理解语法并找出使用不同命令的最方便的方法。我认为在这种情况下,按行 %>% 过滤器对我来说是最直观的理解。
-
rowwise应该比矢量化选项慢 -
感谢您指出这一点。我认为现在速度不是问题(数据表非常小),但随着我对编码越来越熟悉,我会牢记这一点。