示例資料:
df1 = data.frame(x1 = rep(c("foo", "bar"), 4),
x2 = rep(c("FOO", "fix", "broke", "fix"), 2))
我想,例如,更改多個不同的字串,在這種情況下的變化foo來done和bar到open。我正在使用stringr和dplyr。是否有可能把一個以上的功能后~,使多種功能在同一行的代碼在所有列運行,而不是像上面對例子across和everything重復:
> 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
uj5u.com熱心網友回復:
我想 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
uj5u.com熱心網友回復:
或者,您也可以使用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
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/336898.html
上一篇:新列的條件創建(變異)
