Home > other >  Is it possible to pass a dictionary as function parameters in R?
Is it possible to pass a dictionary as function parameters in R?

Time:10-07

I have a function with many parameters which I call during some apply method somewhere deep down my script. I thought it might be easier to save the parameter settings in some variable at the top of my script and call the variable with the parameter settings during the function call.

In mirror to this question in Python, this is what I am looking for:

# warning: pseudo-code!
params <- {'param1': 1, 'param2': 'str', 'param3':TRUE} 

myfunc <- function(param1 ,param2, param3){
    return(param1 ,param2, param3) 
}

myfunc(params)
> 1, 'str', TRUE 

I had a look at this question about dictionary functionalities in R, but many of the packages listed never made it to CRAN.

So my question: Is there a way to pass function parameters as a dictionary in a CRAN-supported way? And if so, is it proper R coding to do so?

CodePudding user response:

One way of calling such a function would be to use do.call that can accept a list with arguments to the function:

param<-c(a=4,b=5,d=55)
fun<-function(a,d,b)
  list(a=a,b=b,d=d)
do.call(fun, as.list(param))
#> $a
#> [1] 4
#> 
#> $b
#> [1] 5
#> 
#> $d
#> [1] 55

Created on 2021-10-06 by the reprex package (v2.0.1)

CodePudding user response:

R doesn’t have a built-in dictionary data structure. The closest equivalent, depending on your use-case, is either a named vector, a named list, or an environment.

So, in your case, you’d define params as

params = list(param1 = 1, param2 = 'str', param3 = TRUE} 

… of course this doesn’t allow using variables for the names, but you can assign the names after the fact to fix that, or use setNames; e.g.:

params = setNames(list(1, 'str', TRUE), paste0('param', 1 : 3))

These work “well enough”, as long as your dictionary keys are strings. Otherwise, you’ll either need a data.frame with a lookup key column and a value column, or a proper data structure.

Correspondingly, there’s also no specific syntactic sugar for the creation of dictionaries. But R’s syntax is flexible, so we can have some fun.

R also doesn’t have a splat operator as in Python, but R has something much more powerful: thanks to metaprogramming, we can generate dynamic function call expressions on the fly. And since calling functions with a list of parameters is such a common operation, R provides a special wrapper for it: do.call.

For instance (using the code from the above link for the syntactic sugar to generate dictionaries):

params = dict('param1': 1, 'param2': 'str', 'param3': TRUE)

myfunc = function (param1, param2, param3) {
    toString(as.list(environment()))
}

do.call('myfunc', params)
# [1] "1, str, TRUE"
  • Related