我正在尝试用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()将dataframe中的"x“替换为"c”,下面是我如何做到的:
data %>%
mutate(time = recode(data$time, str_detect(data$time, "x") = "c"))但这不管用:
错误:意外的'=‘in:"data %>%发生变异(time=recode(数据$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")有办法让这两个功能相互配合吗?
发布于 2018-04-04 14:31:13
如果您希望在这方面尽可能简单,我将使用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”的整个值,只需添加一些regex:
data %>%
mutate(time = str_replace(time, ".*x.*", "c"))regex:.*的细分表示匹配至少0次的任何字符(除\n外)。我们将.*放在x的前面和后面,这样如果有任何来自'x‘的前导或尾随字符,它们仍然会被捕获。
https://stackoverflow.com/questions/49653607
复制相似问题