Mariano Mariano - 2 months ago 7
R Question

Matrix as element of a dataframe in R

I have an lapply function that iterates over a list of elements. For each element, the result is a matrix. Based on the list of elements and the list of matrixes, I would like to return a list of dataframes of the form

element1, matrix1
element2, matrix2
...
...
elementn, matrixn


Example:

e <- list(1,2)
r <- lapply(e, function(x) matrix(ncol = x, nrow = x))


I would like to get a list with these elements

(1, matrix(1x1))
(2, matrix(2x2))

Answer

You can construct data frames in the lapply function, with I(list(...)) which can wrap the matrix as one element in the data frame:

r <- lapply(e, function(x) data.frame(element = x, mat = I(list(matrix(ncol = x, nrow = x)))))

This gives a list of data frames:

r
# [[1]]
#   element mat
# 1       1  NA

# [[2]]
#   element          mat
# 1       2 NA, NA, ....

You can rbind the result together with do.call(rbind, ...):

do.call(rbind, r)
#   element          mat
# 1       1           NA
# 2       2 NA, NA, ....