tc_*_*ata 4 r stringr dplyr tidyverse
我正在尝试使用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"
)
Run Code Online (Sandbox Code Playgroud)
我想通过“ c”替换数据框中的“ x” str_detect(),这是我的操作方法:
data %>%
mutate(time = recode(data$time, str_detect(data$time, "x") = "c"))
Run Code Online (Sandbox Code Playgroud)
但这不起作用:
错误:意外出现“ =”,位于:“数据%>%mutate(时间=重新编码(数据$时间,str_detect(数据$时间,“ x”))=“
显然,R不知道如何处理last =,但我相信它必须存在于recode函数中,如此处所示:
recode(data$time, "x" = "c")
Run Code Online (Sandbox Code Playgroud)
这可以正确执行,如下所示:
str_detect(data$time, "x")
Run Code Online (Sandbox Code Playgroud)
但这不是:
recode(data$time, str_detect(data$time, "x") = "c")
Run Code Online (Sandbox Code Playgroud)
有没有办法使这两个功能相互配合?
如果您想做到这一点尽可能简单,我会使用 gsub
library(dplyr)
data %>%
mutate(time = gsub("x", "c", time))
Run Code Online (Sandbox Code Playgroud)
那消除了recode和的使用str_detect
如果您对使用设定了硬性规定stringr,则应该使用str_replace而不是str_detect:
data %>%
mutate(time = str_replace(time, "x", "c"))
Run Code Online (Sandbox Code Playgroud)
如果要替换包含“ x”的整个值,则只需添加一些正则表达式即可:
data %>%
mutate(time = str_replace(time, ".*x.*", "c"))
Run Code Online (Sandbox Code Playgroud)
正则表达式的细分:.*代表至少匹配0次的任何字符(\ n除外)。我们将.*x放在x的前面和后面,这样,如果'x'中有任何前导或尾随字符,它们仍然会被捕获。