简体   繁体   中英

Provide arguments to multiple parameters from a single object without altering the function call?

Is there any way to provide multiple inputs to a function as a single object?

Example

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 (ie no using do.call() ). Is there a way?

That is, the function must not change, the way it is called must not change (ie no using do.call() or otherwise changing the function)

Desired result

I need to change inputs to anything, so that

funct(inputs)
# [1] 14

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM