2

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])

?

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

1

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))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.