我正在寻找关于如何自动化大量分组和汇总任务的建议。
我执行了4列的dplyr分组,然后在此基础上总结了第五列。我分组的4个列名有936个组合。这意味着我需要执行分组和汇总936次。
数据帧:
mydata <- read.table(header=TRUE, text="
type from to name price
a abc xyz new 10
a abc xyz new 15
a abc xyz new 11
a abc xyz new 12
a abc xyz new 10
a efg hce old 13
a efg hce old 14
a efg hce old 15
b abc hce old 18
b abc hce old 19
b abc hce old 25
b abc ijk new 20
b abc ijk new 25
b efg ijk old 12
b efg ijk old 18
b efg ijk old 14
b efg ijk old 12
b efg lmn old 13
b efg lmn old 18
b efg lmn old 19
b efg lmn old 19
")
分组和汇总:
file_1 <- mydata %>% filter(type=="a" & from=="abc" & to=="xyz" & name="new") %>% group_by(price) %>% summarise(price=median(price), n=n())
……
file_n <- mydata %>% filter(type=="b" & from=="efg" & to=="lmn" & name="old") %>% group_by(price) %>% summarise(price=median(price), n=n())
输出file_1包含2个变量: 1.所有价格,2.各个价格的出现次数:
head(file_1)
前4个变量名称组合的数量,以及输出文件的数量:
n_combinations <- mydata %>% group_by(type, from, to, name) %>% summarise(n=n())
dim(n_combinations)[1]
在真实文件中,每种组合都有数百种不同的价格。
我知道创建936个输出文件是不现实的,但我想知道您将如何处理这样的任务。我正在考虑一个多达100种组合的样本来进行分析。
非常感谢!
发布于 2020-08-09 03:40:13
在我看来
mydata %>%
group_by(type, from, to, name) %>%
summarise(price=median(price), .groups="drop")
# A tibble: 6 x 5
type from to name price
<fct> <fct> <fct> <fct> <dbl>
1 a abc xyz new 11
2 a efg hce old 13.5
3 b abc hce old 18
4 b abc ijk new 20
5 b efg ijk old 12
6 b efg lmn old 13
您可以随心所欲,并且对type
、from
和name
的新组合具有强大的抵抗力。如果您不想要所有可能的组合,您可以只过滤结果数据集。
欢迎来到SO并做得很好,因为它生成了一个比大多数新用户管理的更好的、简单的、自包含的最小工作示例!
https://stackoverflow.com/questions/63319461
复制相似问题