我正在尝试使用 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()
用“c”替换数据框中的“x”这是我的方法: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))
这消除了使用
recode
和 str_detect
如果您一心想使用
stringr
,那么你应该使用 str_replace
而不是 str_detect
:data %>%
mutate(time = str_replace(time, "x", "c"))
如果要替换包含“x”的整个值,则只需添加一些正则表达式:
data %>%
mutate(time = str_replace(time, ".*x.*", "c"))
正则表达式分解:
.*
表示至少匹配 0 次的任何字符(除了\n)。我们把.*
在 x 的前面和后面,这样如果 'x' 有任何前导或尾随字符,它们仍然会被捕获。
关于r - dplyr::recode 与 stringr::str_detect() 结合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49653607/