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

How do I pass multiple columns from a dataframe as individual arguments to a custom function in R

I have a dataframe with variable number of columns. I want to pass

for instance let’s say I have the dataframe df and I want to pass columns a and b as individual arguments to my custom function; but the issue is that the list of column names of interest changes depending on the outcome of another operation and could be any lemgth etc.

df <- tibble(a = c(1:3), b = c(4:6), c=(7:9), d=c(10:12))
custom_function <- function(...){ do something }
custom_function(df$a, df$b)

I haven’t found a clean way to achieve this. Any help would be great.

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

UPDATE

for better clarity I need to add that the challenge is the fact the list of columns of interest is retrieved from another variable. for instance col_names <- c("a","b")

>Solution :

We can capture the ... as a list can then apply the function within do.call

custom_function <- function(fn, data = NULL, ...) {

   args <- list(...)
   if(length(args) == 1 && is.character(args[[1]]) && !is.null(data)) {
      args <- data[args[[1]]]
}
  
   
    do.call(fn, args)

}
custom_function(pmax, df$a, df$b)
[1] 4 5 6

and we can pass ridge

> custom_function(ridge, df$a, df$b)
   [,1] [,2]
[1,]    1    4
[2,]    2    5
[3,]    3    6
attr(,"class")
[1] "coxph.penalty"
...

> custom_function(ridge, data = df, c("a", "b"))
  a b
[1,] 1 4
[2,] 2 5
[3,] 3 6
attr(,"class")
[1] "coxph.penalty"
attr(,"pfun")
...

> custom_function(ridge, data = df, col_names)
     a b
[1,] 1 4
[2,] 2 5
[3,] 3 6
attr(,"class")
...
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