我想根据以下结果创建一个新专栏str_detect
跨多列使用across
.
例如,在下面的测试数据中,我想在以“job”开头的列中搜索“No job”,如果在任何列中检测到该字符串,则返回 1,如果未检测到,则返回 0。
test_data <- data.frame("job1" = c('Sales','Baker','Blacksmith','Brewer'),
"job2" = c('Mailman','Jockey','Jobhunter',"No job"),
"id" = c("id_1", "id_2", "id_3", "id_4"))
# Output I'd like:
# job1 job2 id no_job
#1 Sales Mailman id_1 0
#2 Baker Jockey id_2 0
#3 Blacksmith Jobhunter id_3 0
#4 Brewer No job id_4 1
我知道我可以unite
以“job”开头的列,然后使用str_detect
在这个新专栏上,如下所示:
test_data2 <- test_data %>%
unite(col = "all_jobs", starts_with("job"), sep = ", ", remove = FALSE) %>%
mutate(no_job = if_else(str_detect(all_jobs, "No job"), 1, 0))
...但我想知道是否有办法使用across
做同样的事情。我尝试过以下的变体,但还没有成功。
test_data2 <- test_data %>%
mutate(no_job = if_else(across(starts_with("job"), str_detect(., "No job")), 1, 0))