【问题标题】:Str_detect multiple columns using acrossstr_detect 多列使用cross
【发布时间】: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))

【问题讨论】:

    标签: r dplyr


    【解决方案1】:

    一个选项可能是:

    test_data %>%
     rowwise() %>%
     mutate(no_job = +any(str_detect(c_across(-id), "No job")))
    
      job1       job2      id    no_job
      <fct>      <fct>     <fct>  <int>
    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
    

    【讨论】:

    • 如果“没有工作”出现在多个列中,您可以使用mutate(no_job = as.numeric(any(str_detect(c_across(-id), "No job"))))
    • 那个mutate() 中的+ 是怎么回事?你能解释一下吗?以前没遇到过,很好奇!!
    • @Dunois 它与as.numeric() 相同,即它只是将逻辑向量转换为数字向量。
    【解决方案2】:

    我遇到了类似的问题,这是使用case_when 的可能解决方案:

    test_data %>% mutate(no_job = case_when(if_any(str_detect(starts_with("job"), "No job"))~1))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-01-11
      • 1970-01-01
      • 1970-01-01
      • 2018-10-05
      • 1970-01-01
      • 2017-11-29
      • 2019-07-31
      • 2013-04-28
      相关资源
      最近更新 更多