Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
449 views
in Technique[技术] by (71.8m points)

r - Split a data frame column containing a list into multiple columns using dplyr (or otherwise)

Consider the following example data

library(dplyr)
tmp <- mtcars %>%
    group_by(cyl) %>%
    summarise(mpg_sum = list(summary(mpg)))

such that mpg_sum contains the min, 1st quartile, median, mean, 3rd quartile, and max of the mpg variable by groups in cyl.

How do I unpack this column into 6 columns with appropriate column names with dplyr, or otherwise?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

We can use data.table. Convert the 'data.frame' to 'data.table' (as.data.table(mtcars)), grouped by 'cyl', we get the summary of 'mpg' and convert it to list

library(data.table)
as.data.table(mtcars)[, as.list(summary(mpg)), by = cyl]
#    cyl Min. 1st Qu. Median  Mean 3rd Qu. Max.
#1:   6 17.8   18.65   19.7 19.74   21.00 21.4
#2:   4 21.4   22.80   26.0 26.66   30.40 33.9
#3:   8 10.4   14.40   15.2 15.10   16.25 19.2

Or using only dplyr, after grouping by 'cyl', we use do to do the same operation as above.

library(dplyr)
mtcars %>%
     group_by(cyl) %>%
     do(data.frame(as.list(summary(.$mpg)), check.names=FALSE) )
#   cyl  Min. 1st Qu. Median  Mean 3rd Qu.  Max.
#  <dbl> <dbl>   <dbl>  <dbl> <dbl>   <dbl> <dbl>
#1     4  21.4   22.80   26.0 26.66   30.40  33.9
#2     6  17.8   18.65   19.7 19.74   21.00  21.4
#3     8  10.4   14.40   15.2 15.10   16.25  19.2

Or using purrr

library(purrr)
mtcars %>% 
     slice_rows("cyl") %>% 
     select(mpg) %>%
     by_slice(dmap, summary, .collate= "cols")

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...