Bob Bob - 3 months ago 8
R Question

In R, why does using do.call change the result?

For example, if I have a multidimensional list object, say, "x"

x <- list(); x[[1]] <- c(1,2,3); x[[2]] <- c(2,3,4);
x[[3]] <- c(3,4,5); x[[4]] <- c(4,5,6)
a <- combn(x,3)


If I want to combine every row in the first column into a single vector, this doesn't give me what I want:

c(a[1:3,1]).


It returns a list with each element an element of the original list. Instead, this works:

do.call(c,a[1:3,1])


According to the help description, all do.call does is execute a function, so why is the result different?

Answer

c(a[1:3,1]) is equivalent here to a[1:3,1] which is equivalent here to a[1:3]. All this does is combine the list, not combine the elements of this list.

do.call executes a function call against a list of arguments, in this case, it executes the c function to combine the elements of a.

What you want is c(a[1:3], recursive = TRUE), which descends through the list recursively combining elements into a single vector.