Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I expand a vector into the arguments of a function in r?

Tags:

r

If I have the function with three individual arguments

fun <- function(a,b,c){
    a+b^2*c
}

How can I call it using a single vector

my_vector <- c(1,2,3)
fun(my_vector)
like image 833
nachocab Avatar asked Apr 22 '12 15:04

nachocab


People also ask

How do you add an argument to a function in R?

Adding Arguments in R We can pass an argument to a function while calling the function by simply giving the value as an argument inside the parenthesis.

Can functions take another function as an argument in R?

Yes. See the Examples section of ? optim and ? integrate for some R functions that accept other functions as arguments.


1 Answers

try this:

> do.call("fun", as.list(my_vector)) [1] 13 
like image 199
kohske Avatar answered Sep 19 '22 21:09

kohske