bjorn2bewild
bjorn2bewild

Reputation: 1019

Multiple function inputs from single object in R?

I would like to use a single object to pass multiple inputs to a function in R, is this possible? MWE:

df <- data.frame(yes = c(10,20), no = c(50,60),maybe = c(100,200))

fxn <- function(x,y,z){
  a = x + y
  b = x + z
  c = y + z
  return(list(a=a,b=b,c=c))
}

foo <- c("rincon","malibu","steamer")
bar <- c("no","maybe")

df[foo] <- fxn(df$yes,df[bar])

In the actual problem, my function has more inputs that are in the default set to NULL. I am working in a dynamic shiny context, so the value and length of bar is changing. Any help for this newbie would be greatly appreciated.

Upvotes: 1

Views: 58

Answers (1)

MrFlick
MrFlick

Reputation: 206411

With base R you can build the call using do.call and create a list() of parameters you want to pass to the function

do.call("fxn", c(list(df$yes), unname(df[bar])))

This would be the same as

fxn(df$yes, df[bar][[1]], df[bar][[2]])

We need to use the unname() because otherwise your parameters would be named "no" and "maybe" while your function is expecting "y" and "z".

The the rlang package, you could do

library(rlang)
eval_tidy(quo(fxn(df$yes, !!!unname(df[bar]))))

That uses the !!! splicing operator like some other languages have. Base R does not have such a syntax.

Upvotes: 3

Related Questions