我在aggregate()中使用了quantile(),见下文。
结果被格式化为数据框,但是,正如您在str()中看到的那样,实际的分位数是列中的列表。如何将输出作为数据框,其中所有“列”都是实际列(即名称(结果) - > “group”“subgroup”“value.0%”“value.25%”“value.50%”“value.75%”“value.100%”
(我不关心实际的名字,我只是想能够使用setNames())
非常感谢任何帮助!
干杯, LUC
n=1000
df <- data.frame(group=sample(c("A", "B", "C"), n, replace=T),
subgroup=sample(c("g1", "g2"), n, replace=T),
value=sample(1:10000, n, replace=T))
head(df)
result <- aggregate(value ~ group + subgroup, df, function(x) quantile(x, probs = seq(0,1, 0.25)))
> result
group subgroup value.0% value.25% value.50% value.75% value.100%
1 A g1 26.00 3088.00 5738.00 7473.00 9852.00
2 B g1 26.00 2450.00 4592.50 7319.00 9989.00
3 C g1 17.00 2989.00 5565.00 7611.00 9944.00
4 A g2 96.00 2843.75 4912.00 7719.50 9815.00
5 B g2 77.00 2802.50 4725.50 6996.75 9950.00
6 C g2 115.00 2606.00 4776.50 7673.25 9878.00
> str(result)
'data.frame': 6 obs. of 3 variables:
$ group : Factor w/ 3 levels "A","B","C": 1 2 3 1 2 3
$ subgroup: Factor w/ 2 levels "g1","g2": 1 1 1 2 2 2
$ value : num [1:6, 1:5] 26 26 17 96 77 ...
..- attr(*, "dimnames")=List of 2
.. ..$ : NULL
.. ..$ : chr "0%" "25%" "50%" "75%" ...