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

查看:21
本文介绍了使用 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.

如何使用 dplyr 或其他方式将此列解压缩为具有适当列名的 6 列?

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

推荐答案

我们可以使用data.table.将'data.frame'转换为'data.table'(as.data.table(mtcars)),按'cyl'分组,我们得到'的summarympg' 并将其转换为 list

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

<小时>

或者使用only 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天全站免登陆