Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

user defined R function that use column names as an argument

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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
...
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading