set.seed(2023)
pid <- 1:30
y1 <- rnorm(30, 10, 10)
y2 <- rnorm(30, 10, 10)
x1 <- rnorm(30, 5, 2)
x2 <- rnorm(30, 5, 2)
x3 <- rnorm(30, 300, 3)
This is minimal reproducible data.
I want to make a function as below.
try <- function(data, a, b) {
data <- data %>%
mutate(paste0(a, b, "manual_mean") = ({{a}} + {{b}}) /2
)
return(data)
}
so, a and b will be column names from data.
t<-try(data2,y1,y2)
and I tried this try() function.
I expect that I have a new column named as "y1y2manualmean"
but it throws an error.
>Solution :
Use the := operator – try is already a function name. So, use a different name as well
f1<- function(data, a, b) {
data %>%
mutate("{{a}}_{{b}}_manual_mean" := ({{a}} + {{b}}) /2
)
}
-testing
> f1(data2, y1, y2)
pid y1 y2 x1 x2 x3 y1_y2_manual_mean
1 1 9.1621564 7.2512294 6.976368 2.2217230 298.5748 8.206693
2 2 0.1705625 22.7665407 4.431874 5.8573400 301.1042 11.468552
3 3 -8.7506732 1.8901966 1.155465 4.4124372 300.3106 -3.430238
4 4 8.1385534 9.5507722 2.652560 9.5599976 301.0390 8.844663
...