【发布时间】:2020-08-13 16:15:11
【问题描述】:
我想使用across 在多个列中基于str_detect 的结果创建一个新列。
例如,在下面的测试数据中,我想在以“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 以“工作”开头的列,然后在新列上使用 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))
【问题讨论】: