Search code examples
rfunctionellipsis

R - Fill the arguments of a function in an ellipsis


I have the following function :

ExampleFunction <- function(ListNumber1, ListNumber2)
{
  OutputData <- list()
  OutputData[[1]] <- rbind.fill(ListNumber1[[1]], ListNumber2[[1]])
  OutputData[[2]] <- rbind.fill(ListNumber1[[2]], ListNumber2[[2]])
  return(OutputData)
}

I want to improve this function introducing the possibility to use a variable number of arguments (i.e. lists in my example). Here is an attempt to do this but I don't see how to fill the arguments of rbind.fill().

ExampleFunctionUpgrade <- function(...)
{
  Arguments <- list(...)
  OutputData <- list()
  VarNames <- paste0("List", seq_along(Arguments))
  for (i in 1:length(Arguments))
  {
    assign(VarNames[i], Arguments[[i]])
  }
  OutputData <- rbind.fill(???)
  return(OutputData)
}

Solution

  • I would try to iterate over the columns within an lapply call that is to be bound together.

    ExampleFunctionUpgrade <- function(...)
    {
      Arguments <- list(...)
      OutputData <- list()
      for(i in 1:length(Arguments[[1]])) {
        OutputData[[i]] <- rbind.fill(lapply(Arguments, '[[', i))
      }
      return(OutputData)
    }
    

    If you don't like 'for loops' you can use two lapply calls.