使用dplyr(或以其他方式)将包含列表的数据框架列分成多个列 [英] Split a data frame column containing a list into multiple columns using dplyr (or otherwise)

查看:117
本文介绍了使用dplyr(或以其他方式)将包含列表的数据框架列分成多个列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下示例数据

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

,使 mpg_sum 包含 mpg 根据 cyl 中的组变量。

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

如何将该列解压缩为6列,并附上相应的列我们可以使用 data.table

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

推荐答案

>。将data.frame转换为data.table( as.data.table(mtcars)),按cyl分组,我们得到总结的mpg,并将其转换为列表

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






或仅使用 dplyr ,通过'cyl'分组后,我们使用 do 执行与上述相同的操作。


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

或使用 purrr

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

这篇关于使用dplyr(或以其他方式)将包含列表的数据框架列分成多个列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆