如何在R中合并含相同行的DataFrame并汇总Freq列
合并R语言DataFrame并按Phenotype累加Freq值
你可以通过分组求和的方式实现需求,而非单纯堆叠数据。以下是两种常用的实现方法:
方法一:使用Base R的aggregate()函数
先将两个数据框堆叠,再以Phenotype为分组依据对Freq求和:
db1 <- data.frame("Phenotype" = c("Intellectul Disability", "Cystic Kidney Disease", "Epilepsy", "Cardiac Disorder"), "Freq" = c(10,2,3,4)) db2 <- data.frame("Phenotype" = c("Kabuki Syndrome", "Cystic Kidney Disease", "Intellectul Disability", "Epilepsy"), "Freq" = c(13,1,0,2)) # 堆叠数据后分组求和 combined <- rbind(db1, db2) bdc <- aggregate(Freq ~ Phenotype, data = combined, sum) # 查看结果 print(bdc)
方法二:使用tidyverse的dplyr包
如果习惯tidyverse风格,可以用bind_rows合并数据,再通过group_by和summarize实现分组求和:
library(dplyr) db1 <- data.frame("Phenotype" = c("Intellectul Disability", "Cystic Kidney Disease", "Epilepsy", "Cardiac Disorder"), "Freq" = c(10,2,3,4)) db2 <- data.frame("Phenotype" = c("Kabuki Syndrome", "Cystic Kidney Disease", "Intellectul Disability", "Epilepsy"), "Freq" = c(13,1,0,2)) bdc <- bind_rows(db1, db2) %>% group_by(Phenotype) %>% summarize(Freq = sum(Freq), .groups = "drop") # 查看结果 print(bdc)
两种方法最终都会得到你期望的结果:
Phenotype Freq 1 Cardiac Disorder 4 2 Cystic Kidney Disease 3 3 Epilepsy 5 4 Intellectul Disability 10 5 Kabuki Syndrome 13
内容的提问来源于stack exchange,提问作者Ar1229
相关产品推荐
相关产品推荐

