Home > Enterprise >  Passing Different Length List Parameters to R Function
Passing Different Length List Parameters to R Function

Time:02-02

I have a user-written function that I want to be able to pass both lists and single parameter arguments to. The lists can be different lengths. The following is a simplified example, where I combined the lists using expand.grid and use map:

fake_dat <-  as.data.frame(matrix(c(1, 2, 3, 4), nrow = 2, byrow = TRUE))

one_lst <- c("a","b")
two_lst <- c("aa","bb")
all_lst <- expand.grid(one_lst, two_lst)

with(all_lst, Map(function(var1, var2, dat, x) {
  print(var1)
  print(var2)
  print(dat[[x]])
}, Var1, Var2, dat=fake_dat, x="V2"))

Using it this way I get the following error:

Error in (function (cond) : 
error in evaluating the argument 'x' in selecting a method for function 'print': subscript out of bounds

However, if I embed the single parameters within list, it seems to work:

with(all_lst, Map(function(var1, var2, dat, x) {
  print(var1)
  print(var2)
  print(dat[[x]])
}, Var1, Var2, dat=list(fake_dat), x=list("V2")))

Is this the appropriate way to use map for my scenario...or is there a better way to accomplish passing some lists (potentially of varying lengths) and some single parameter arguments to a function?

CodePudding user response:

It's unclear exactly what you're trying to accomplish, but the error is because fake_dat has length = 2 (number of columns in the data.frame), so Map passes those columns to the function one at a time. When the first column is passed, "V2" is out of bounds. This is why wrapping fake_dat with list() resolves the error--the whole data.frame is passed to the function because list(fake_dat) has length 1. (Wrapping "V2" with list() does nothing here.)

with(all_lst, Map(function(var1, var2, dat, x) {
  print(var1)
  print(var2)
  print(dat[[x]])
}, Var1, Var2, dat=list(fake_dat), x="V2"))

Note that if the vector arguments of Map are of different lengths, the shorter arguments are recycled.

  • Related