library(dplyr)
func <- function(data, col){
data <- data %>%
mutate(col = {{col}}*2)
return(data)
}
df <- data.frame(x = c(1:8), y = c("hello", "world", "sun", "winter"))
func(df, x)
x y col
1 1 hello 2
2 2 world 4
3 3 sun 6
4 4 winter 8
5 5 hello 10
6 6 world 12
7 7 sun 14
8 8 winter 16
我想要更新 x 列:
x y
1 2 hello
2 4 world
3 6 sun
4 8 winter
5 10 hello
6 12 world
7 14 sun
8 16 winter
我尝试了很多方法都没有成功,有人有什么建议吗?提前致谢!
最佳答案
我们需要赋值(:=
)运算符
func <- function(data, col){
data %>%
mutate({{col}} := {{col}}*2)
}
func(df, x)
-输出
# x y
#1 2 hello
#2 4 world
#3 6 sun
#4 8 winter
#5 10 hello
#6 12 world
#7 14 sun
#8 16 winter
关于r - 创建带有 mutate(x = x*2) 的函数(data, x) 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65132906/