Reputation: 52258
Is there any way to provide multiple inputs to a function as a single object?
Suppose a function expects 2 inputs
funct <- function(x, y) {
x * y
}
funct(2, 7)
# [1] 14
Can we provide both inputs as one object somehow?
inputs <- c(2, 7)
funct(inputs)
Error in funct(inputs) : argument "y" is missing, with no default
inputs <- list(2, 7)
funct(inputs)
Error in funct(inputs) : argument "y" is missing, with no default
I want to achieve this only by changing the input, not by editing the function nor function call (i.e. no using do.call()
). Is there a way?
That is, the function must not change, the way it is called must not change (i.e. no using do.call()
or otherwise changing the function)
I need to change inputs
to anything, so that
funct(inputs)
# [1] 14
Upvotes: 0
Views: 71
Reputation: 159
So from your question, I understand that u need to pass the value of both x,y using a single parameter to the function.
The best way to accomplish this my passing a list or dictionary and using the same inside the function:
if you pass it as a list or array then do this
`funct <- function(x) {
x[[1]] * x[[2]]
}`
`inputs <- list(2, 7)
funct(inputs)`
if you are passing it as a dictionary, you will have the advantage of naming the values:
`funct <- function(input) {
library(hash)
input[["x"]] * input[["y"]]
}`
`library(hash)
inputs <- hash()
inputs[["x"]] <- 2
inputs[["y"]] <- 7
funct(inputs)`
Or you can do the following with your existing function:
do.call(funct,list(2,7))
Upvotes: 1