简体   繁体   中英

Is there a way in R to create summary statistics table from a list of data

I am trying to make a summary table of my data using table1::table1 function.

I can get the below code to work as expected.

DF = list('A' = rnorm(100, mean = 1),
          'B' = rnorm(100, mean = 2),
          'C' = rnorm(100, mean = 3))
table1::table1(~A+B+C, data=DF, overall = 'List 1')

I am trying to do the same thing as above but instead, I have a list of data that I want to combine and have the columns as List 1 and List 2, with the same summary statistics from A, B, C as the rows.

DF = NULL
DF[['List 1']] = list('A' = rnorm(100, mean = 1),
          'B' = rnorm(100, mean = 2),
          'C' = rnorm(100, mean = 3))

DF[['List 2']] = list('A' = rnorm(100, mean = 1),
          'B' = rnorm(100, mean = 2),
          'C' = rnorm(100, mean = 3))

Does anyone have any suggestions or know of a better way to accomplish this?

We can use transpose from purrr and flatten or unlist the list elements to be a list of 3

library(purrr)
DF2 <- transpose(DF) %>% 
            map(flatten_dbl)

NOTE: DF is the second dataset in the OP's post

Now, we test with table1

table1::table1(~A+B+C, data=DF2, overall = 'List 1')

-output

在此处输入图像描述


If we need to create a two column table, convert the list of list of vectors to a single data.frame while creating a column with the names of the outer list element

new_DF <- do.call(rbind, Map(cbind, nm1 = names(DF), 
         lapply(DF, as.data.frame)))
row.names(new_DF) <- NULL

table1::table1(~ A + B + C |nm1, data = new_DF)

-output

在此处输入图像描述

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