Mar*_*ies 5 r function stringr dplyr
示例数据:
df1 = data.frame(x1 = rep(c("foo", "bar"), 4),
x2 = rep(c("FOO", "fix", "broke", "fix"), 2))
Run Code Online (Sandbox Code Playgroud)
例如,我想更改多个不同的字符串,在本例中更改foo为done和。我正在使用和。是否可以在 后面放置多个函数,以便在同一行代码中的所有列上运行多个函数,而不是像上面重复和的示例那样:baropenstringrdplyr~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
Run Code Online (Sandbox Code Playgroud)
我想 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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2034 次 |
| 最近记录: |