Reputation: 3983
So, I'm trying to pass lists to a function that returns a data frame via mapply
, then use do.call
to rbind
them all together into a single data frame.
Here's some dummy code:
var_1 <- list(1, 2)
var_2 <- list(3, 4)
output <- do.call(
rbind,
mapply(
function(x, y) {return(data.frame(x, y, x+y))},
var_1,
var_2
)
)
Expected result: a data frame with 2 rows and 3 columns.
Actual result: a 6x1 matrix.
Any ideas on what I'm doing wrong here?
Upvotes: 1
Views: 1153
Reputation: 206401
When using do.call
you need to pass in a list of parameters. Currently your mapply
call doesn't reuturn a list, it simplifies the result into a matrix. What you want is to prevent the simplification. You can either set the SIMPLIFY=
parameter
output <- do.call(
rbind,
mapply(
function(x, y) {return(data.frame(x, y, x+y))},
var_1,
var_2, SIMPLIFY=FALSE
)
)
or just use Map()
which always returns a list
output <- do.call(
rbind,
Map(
function(x, y) {return(data.frame(x, y, x+y))},
var_1,
var_2
)
)
Upvotes: 5