Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Convert list of matrices into a single summary data frame

I have a list of matrices.

# Sample data
m1 <- matrix(c(5, 2, 8, 3, 10, 3), nrow = 2, ncol = 3, dimnames = list(c("Mean", "SD"), c("Apples", "Oranges", "Bananas")))
m2 <- matrix(c(4, 1, 7, 2, 9, 2), nrow = 2, ncol = 3, dimnames = list(c("Mean", "SD"), c("Apples", "Oranges", "Bananas")))
m3 <- matrix(c(6, 3, 9, 4, 11, 4), nrow = 2, ncol = 3, dimnames = list(c("Mean", "SD"), c("Apples", "Oranges", "Bananas")))

# Create a list of data frames
matrix_list <- list(m1 = m1, m2 = m2, m3 = m3)

I want to combine the matrices in the list to make a summary data frame with the following structure.

    Apples_Mean Apples_SD Oranges_Mean Oranges_SD Bananas_Mean Bananas_SD
m1            5         2            8          3           10          3
m2            4         1            7          2            9          2
m3            6         3            9          4           11          4

How can I do this?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

With base R, you can use xtabs + Map + as.data.frame like below

xtabs(
    Freq ~ m + paste0(Var2, "_", Var1),
    do.call(
        rbind,
        Map(
            \(x, y) cbind(
                m = x,
                as.data.frame(as.table(y))
            ),
            names(matrix_list),
            matrix_list
        )
    )
)

which gives

    paste0(Var2, "_", Var1)
m    Apples_Mean Apples_SD Bananas_Mean Bananas_SD Oranges_Mean Oranges_SD
  m1           5         2           10          3            8          3
  m2           4         1            9          2            7          2
  m3           6         3           11          4            9          4
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading