【发布时间】:2020-06-12 17:03:01
【问题描述】:
我想以这种格式生成“宽”数据汇总表:
---- Centiles ----
Param Group Mean SD 25% 50% 75%
Height 1 x.xx x.xxx x.xx x.xx x.xx
2 x.xx x.xxx x.xx x.xx x.xx
3 x.xx x.xxx x.xx x.xx x.xx
Weight 1 x.xx x.xxx x.xx x.xx x.xx
2 x.xx x.xxx x.xx x.xx x.xx
3 x.xx x.xxx x.xx x.xx x.xx
我可以在 dplyr 0.8.x 中做到这一点。我可以通用地做到这一点,使用一个函数可以处理具有任意数量的级别的任意分组变量和总结任意数量的具有任意名称的变量的任意统计信息。通过使我的数据tidy,我获得了这种级别的灵活性。这不是这个问题的目的。
首先,一些玩具数据:
set.seed(123456)
toy <- tibble(
Group=rep(1:3, each=5),
Height=1.65 + rnorm(15, 0, 0.1),
Weight= 75 + rnorm(15, 0, 10)
) %>%
pivot_longer(
values_to="Value",
names_to="Parameter",
cols=c(Height, Weight)
)
现在,一个简单的汇总函数和一个助手:
quibble2 <- function(x, q = c(0.25, 0.5, 0.75)) {
tibble(Value := quantile(x, q), "Quantile" := q)
}
mySummary <- function(data, ...) {
data %>%
group_by(Parameter, Group) %>%
summarise(..., .groups="drop")
}
所以我可以这么说
summary <- mySummary(toy, Q=quibble2(Value), Mean=mean(Value, na.rm=TRUE), SD=sd(Value, na.rm=TRUE))
summary %>% head()
给予
# A tibble: 6 x 5
Parameter Group Q$Value $Quantile Mean SD
<chr> <int> <dbl> <dbl> <dbl> <dbl>
1 Height 1 1.45 0.25 1.54 0.141
2 Height 1 1.49 0.5 1.54 0.141
3 Height 1 1.59 0.75 1.54 0.141
4 Height 2 1.64 0.25 1.66 0.0649
5 Height 2 1.68 0.5 1.66 0.0649
6 Height 2 1.68 0.75 1.66 0.0649
这就是我需要的摘要,但它的格式很长。而Q 是df-col。这是一个小标题:
is_tibble(summary$Q)
[1] TRUE
所以pivot_wider 似乎不起作用。我可以使用nest_by() 来获得每组一行的格式:
toySummary <- summary %>% nest_by(Group, Mean, SD)
toySummary
# Rowwise: Group, Mean, SD
Group Mean SD data
<int> <dbl> <dbl> <list<tbl_df[,2]>>
1 1 1.54 0.141 [3 × 2]
2 1 78.8 10.2 [3 × 2]
3 2 1.66 0.0649 [3 × 2]
4 2 82.9 9.09 [3 × 2]
5 3 1.63 0.100 [3 × 2]
6 3 71.0 10.8 [3 × 2]
但是现在百分位数的格式更加复杂了:
> toySummary$data[1]
<list_of<
tbl_df<
Parameter: character
Q :
tbl_df<
Value : double
Quantile: double
>
>
>[1]>
[[1]]
# A tibble: 3 x 2
Parameter Q$Value $Quantile
<chr> <dbl> <dbl>
1 Height 1.45 0.25
2 Height 1.49 0.5
3 Height 1.59 0.75
它看起来像list,所以我想某种形式的lapply 可能会起作用,但是有没有我还没有发现的更整洁的解决方案?我在研究这个问题时发现了几个我不知道的新动词(chop、pack、rowwise()、nest_by 等),但似乎没有一个能满足我的需求:理想情况下,a tibble 有 6 行(由唯一的 Group 和 Parameter 组合定义)和 Mean、SD、Q25、Q50 和 Q75 的列。
为了澄清前两个建议的答案:获得我的玩具示例生成的确切数字不如找到一个 通用技术 从 df-col(s) 转移到 @ 987654349@ 在dplyr v1.0.0 中返回到我的示例说明的一般形式的广泛数据摘要。
【问题讨论】: