Search code examples
rlistargumentsellipsisvariadic-functions

How to use a 'list' object when a '...' argument is required?


In many R functions the ... argument is used to supply several objects. How can I supply a list object in a ... argument?

For example:

x1 <- head(iris)
x2 <- tail(iris)
rbind(x1, x2)
#    Sepal.Length Sepal.Width Petal.Length Petal.Width   Species
#1            5.1         3.5          1.4         0.2    setosa
#2            4.9         3.0          1.4         0.2    setosa
#3            4.7         3.2          1.3         0.2    setosa
#4            4.6         3.1          1.5         0.2    setosa
#5            5.0         3.6          1.4         0.2    setosa
#6            5.4         3.9          1.7         0.4    setosa
#145          6.7         3.3          5.7         2.5 virginica
#146          6.7         3.0          5.2         2.3 virginica
#147          6.3         2.5          5.0         1.9 virginica
#148          6.5         3.0          5.2         2.0 virginica
#149          6.2         3.4          5.4         2.3 virginica
#150          5.9         3.0          5.1         1.8 virginica

But assume that I have the x1 and x2 data frames in a list. How can I use that list with the ... argument in rbind?

I've already tried the following, with no success:

rbind(list(x1, x2))
rbind(substitute(list(x1, x2))[-1])
rbind(unlist(list(x1, x2)))

In each of these cases the result is NOT as that from rbind(x1, x2). What am I missing?

UPDATE1:
As suggested in the answers, do.call(rbind, list(x1, x2)) seems to work perfectly in this case. However, I'm wondering if it's possible to avoid do.call machinery. In other words, is it possible to convert list(x1, x2) so that ... understands it correctly?


Solution

  • do.call is what you use in this case.

    df1 <- head(iris)
    df2 <- tail(iris)
    l <- list(df1, df2)
    
    do.call(rbind, l)
    ##     Sepal.Length Sepal.Width Petal.Length Petal.Width   Species
    ## 1            5.1         3.5          1.4         0.2    setosa
    ## 2            4.9         3.0          1.4         0.2    setosa
    ## 3            4.7         3.2          1.3         0.2    setosa
    ## 4            4.6         3.1          1.5         0.2    setosa
    ## 5            5.0         3.6          1.4         0.2    setosa
    ## 6            5.4         3.9          1.7         0.4    setosa
    ## 145          6.7         3.3          5.7         2.5 virginica
    ## 146          6.7         3.0          5.2         2.3 virginica
    ## 147          6.3         2.5          5.0         1.9 virginica
    ## 148          6.5         3.0          5.2         2.0 virginica
    ## 149          6.2         3.4          5.4         2.3 virginica
    ## 150          5.9         3.0          5.1         1.8 virginica