Mariano Mariano - 1 month ago 5x
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


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))


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:

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

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

You can rbind the result together with, ...):, r)
#   element          mat
# 1       1           NA
# 2       2 NA, NA, ....