R: pass a character vector to a function instead of a long list of arguments

I am writing an R package that calls C code using the .C () function. I need to pass over 50 arguments to .C (), which seriously bloats my code and is error prone. Instead of type

output <- .C("my_dynlib", arg2, arg3, arg4, arg5, arg6, ..., arg53)

      

I would rather have a character vector of myNames

additional arguments to send to .C () and do something like

f <- Vectorize(as.symbol, "x")
mySymbols <- f(myNames)
output <- .C("my_dynlib", mySymbols)

      

But that's not exactly what I want, because mySymbols is a list. Is there a way to compactly pass a set of arguments to a function that I don't want to rewrite?

Footnote: I'm guessing some of you will suggest passing more complex arguments using .Call, .External or Rcpp, but that's more important than I want to deal with right now.


Edit: what if I want to myNames

point to slots in s3 or s4 object?

Suppose I want to use symbols related to class slots in a data frame.

> y = data.frame(a = 1:4, b = 5:8)
> myNames = paste("y@", slotNames(y), sep = "")
> mySymbols = lapply(myNames, as.symbol)
> str(mySymbols)
List of 4
 $ : symbol y@.Data
 $ : symbol y@names
 $ : symbol y@row.names
 $ : symbol y@.S3Class

      

I am using do.call like @josilber but do.call doesn't recognize characters

> do.call(print, mySymbols)
Error in (function (x, ...)  : object 'y@.Data' not found

      

although I can use these symbols manually.

> y@.Data
[[1]]
[1] 1 2 3 4

[[2]]
[1] 5 6 7 8 

      

+3


source to share


1 answer


If you have a list of objects that you want to pass to a function, you can do so with a function do.call

. In your case, it looks like this:



do.call(".C", c("my_dynlib", mySymbols))

      

+2


source







All Articles