【问题标题】:How can I rewrite in a more efficient way str_detect()?如何以更有效的方式重写 str_detect()?
【发布时间】:2022-11-04 21:18:35
【问题描述】:
mutate(method = cur_group_id(),
           method = paste0("M", method)) %>% 
    mutate(method = case_when(
      str_detect(variable, "testhc35") ~ "M2",
      str_detect(variable, "testhc36") ~ "M2",
      str_detect(variable, "testhc37") ~ "M2",
      str_detect(variable, "testhi1") ~ "M2",
      str_detect(variable, "testhi2") ~ "M2",
      str_detect(variable, "testhi3") ~ "M2",
      method == "M1" ~ "M1",
      str_detect(variable, "testhc38") ~ "M3",
      str_detect(variable, "testhc39") ~ "M3",
      str_detect(variable, "testhc40") ~ "M3",
      str_detect(variable, "testhi4") ~ "M3",
      str_detect(variable, "testhi5") ~ "M3",
      str_detect(variable, "testhi6") ~ "M3")) %>% 
    unite(method_trait, c("method", "trait"), sep = "")

我相信我可以用 str_detect() 完全检测前 6 行,然后将最后 6 行作为一行。但我不知道该怎么做。

【问题讨论】:

  • 你能分享你的数据样本吗?

标签: r regex dplyr stringr


【解决方案1】:

您可以更简洁地使用范围:

...
str_detect(variable, "testhc3[5-7]")  ~ "M2",
str_detect(variable, "testhi[1-3]")   ~ "M2",
method == "M1"                        ~ "M1",
str_detect(variable, "testhc3[8-9]")  ~ "M3",
str_detect(variable, "testhc40")      ~ "M3"
str_detect(variable, "testhi[4-6]")   ~ "M3"
...

然后你可以混入 or (|) 运算符:

...
str_detect(variable, "testh(c3[5-7]|i[1-3])")      ~ "M2",
method == "M1"                                     ~ "M1",
str_detect(variable, "testh(c3[8-9]|i[4-6]|c40)")  ~ "M3",
...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-08-27
    • 2012-01-06
    • 1970-01-01
    • 2022-01-25
    • 2015-03-03
    • 1970-01-01
    • 2017-05-30
    • 2012-07-18
    相关资源
    最近更新 更多