C_Z_
C_Z_

Reputation: 7806

Multiple inputs to a function

I might just be missing a very obvious solution, but here's my question:

I have a function that takes a few inputs. I'm generating these inputs by getting values from a dataframe. What's the cleanest way to input my values into the function?

Let's say I have the function

sampleFunction<-function(input1, input2, input3){
  return((input1+input2)-input3)
}

And an input that consists of a few columns of a row of a dataframe

sampleInput <- c(1,2,3)

I'd like to input the three values of my sampleInput into my sampleFunction. Is there a cleaner way than just doing

sampleFunction(sampleInput[1], sampleInput[2], sampleInput[3])

?

Upvotes: 2

Views: 642

Answers (2)

Steph Locke
Steph Locke

Reputation: 6146

I would consider using the package data.table.

It doesn't directly answer the question of how to pass in a vector, however it does help address the greater contextual question of using the function for the rows in a table in a typing-efficient manner. You could do it in data.frame but your code would still look similar to what you're trying to avoid.

If you made your data.frame a data.table then your code would look like:

library(data.table)
sampleFunction<-function(input1, input2, input3){
  return((input1+input2)-input3)
}

mydt[,sampleFunction(colA,colB,colC)] # do for all rows
mydt[1,sampleFunction(colA,colB,colC)] # do it for just row 1

You could then add that value as a column, return it independently etc

Upvotes: 2

ahmohamed
ahmohamed

Reputation: 2970

try

do.call(sampleFunction, sampleInput)

P.S sampleInput must be a list. If it is vector use as.list

do.call(sampleFunction, as.list(sampleInput))

Upvotes: 1

Related Questions