dplyr::recode 结合 stringr::str_detect()

dplyr::recode in conjunction with stringr::str_detect()

我正在尝试用 dplyr::recode()stringr::str_detect() 重新编码一个字符变量。我意识到这可以用 dplyr::case_when() 来完成,如此处记录:https://community.rstudio.com/t/recoding-using-str-detect/5141,但我相信必须有一种方法可以通过 recode().

来完成

考虑这个案例:

library(tidyverse)
rm(list = ls())

data <- tribble(
  ~id, ~time,
  #--|--|
  1, "a",
  2, "b",
  3, "x"
)

我想通过 str_detect() 将数据框中的 "x" 替换为 "c",我会这样做:

data %>% 
 mutate(time = recode(data$time, str_detect(data$time, "x") = "c"))

但这不起作用:

Error: unexpected '=' in: "data %>% mutate(time = recode(data$time, str_detect(data$time, "x") ="

显然 R 不知道如何处理最后一个 =,但我相信它必须存在于重新编码功能中,如此处所示:

recode(data$time, "x" = "c")

这会正确执行,如下所示:

str_detect(data$time, "x")

但这不是:

recode(data$time, str_detect(data$time, "x") = "c")

有没有办法让这两个函数相互配合?

如果你想要尽可能简单,我会使用 gsub

library(dplyr)
data %>% 
  mutate(time = gsub("x", "c", time))

这消除了 recodestr_detect

的使用

如果您执意要使用 stringr,那么您应该使用 str_replace 而不是 str_detect:

data %>% 
  mutate(time = str_replace(time, "x", "c"))

如果要替换包含 'x' 的整个值,则只需添加一些正则表达式:

data %>% 
  mutate(time = str_replace(time, ".*x.*", "c"))

正则表达式分解:.* 表示任何字符(\n 除外)至少匹配 0 次。我们将 .* 放在 x 的前后,这样如果 'x' 中有任何前导或尾随字符,它们仍会被捕获。