简体   繁体   中英

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

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, ....

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM