我正在尝试使用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)
有没有办法使这两个功能相互配合?
我非常喜欢在 R 中使用 magrittr 管道 %>%,并尝试尽可能频繁/高效地使用它们。我经常需要定位管道链中的特定列,例如更改列类型。这导致我必须打破链条/我的工作流程,因为我只需要定位特定列而不是整个数据框。
考虑以下示例:
library(tidyverse)
rm(list = ls())
a <- c(1:20)
b <- rep(c("a", "b"), 10)
df <- data_frame(a, b) %>%
rename(info = b) %>%
recode(x = df$info, "a" = "x") #I'd like to target only the df$info column here
Run Code Online (Sandbox Code Playgroud)
这显然不起作用,因为 dplyr 不希望我更改管道链中函数的 x = 参数。
library(tidyverse)
rm(list = ls())
a <- c(1:20)
b <- rep(c("a", "b"), 10)
df <- data_frame(a, b) %>%
rename(info = b)
df$info <- df$info %>% #this works as expected, but is …Run Code Online (Sandbox Code Playgroud)