将多个函数放入单个 dplyr 中,跨所有内容进行变异,例如更改多个不同的字符串

Put multiple functions into a single dplyr mutate across everything e.g. change mulitple different strings

示例数据:

df1 = data.frame(x1 = rep(c("foo", "bar"), 4),
                 x2 = rep(c("FOO", "fix", "broke", "fix"), 2))

例如,我想更改多个不同的字符串,在本例中,将 foo 更改为 done,将 bar 更改为 open。我正在使用 stringrdplyr。是否可以在 ~ 之后放置多个函数,以便在同一行代码中的所有列中有多个函数 运行,而不是像上面的示例那样 acrosseverything 重复:

> df1%>%
+   mutate(across(everything(), ~ str_replace(.,"(?i)bar", "open")),
+          across(everything(), ~ str_replace(., "(?i)foo", "done")))
    x1    x2
1 done  done
2 open   fix
3 done broke
4 open   fix
5 done  done
6 open   fix
7 done broke
8 open   fix

我想 tidyverse 的方法是使用管道运算符将多个函数链接在一起。这意味着您只需调用 across 一次。

df1 %>% 
   mutate(across(everything(), ~ str_replace(.,"(?i)bar", "open") %>% 
                                 str_replace("(?i)foo", "done")))
    x1    x2
1 done  done
2 open   fix
3 done broke
4 open   fix
5 done  done
6 open   fix
7 done broke
8 open   fix

或者,您也可以使用 str_replace_all -

library(dplyr)
library(stringr)

df1 %> 
    mutate(across(.fns = ~str_replace_all(., c("(?i)bar" = "open", "(?i)foo" = "done"))))

#    x1    x2
#1 done  done
#2 open   fix
#3 done broke
#4 open   fix
#5 done  done
#6 open   fix
#7 done broke
#8 open   fix