在多个数据框中应用聚合列R

编程入门 行业动态 更新时间:2024-10-08 22:14:08
本文介绍了在多个数据框中应用聚合列R的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我在R的列表中有几个数据框.我想总结一下每个DF中的条目.我试图陷入困境,这将是我的首选方式(尽管如果有更好的解决方案,我将很高兴知道它以及原因).

I have several dataframes in a list in R. There are entries in each of those DF I would like to summarise. Im trying to get into lapply so that would be my preferred way (though if theres a better solution I would be happy to know it and why).

我的样本数据:

df1 <- data.frame(Count = c(1,2,3), ID = c("A","A","C")) df2 <- data.frame(Count = c(1,1,2), ID = c("C","B","C")) dfList <- list(df1,df2) > head(dfList) [[1]] Count ID 1 1 A 2 2 A 3 3 C [[2]] Count ID 1 1 C 2 1 B 3 2 C

我试图用lapply实现这一点

I tried to implement this in lapply with

dfList_agg<-lapply(dfList, function(i) { aggregate(i[[1:length(i)]][1L], by=list(names(i[[1:length(i)]][2L])), FUN=sum) })

但是这给我一个错误参数必须具有相同的长度".我在做什么错了?

However this gives me a error "arguments must have same length". What am I doing wrong?

我想要的输出将是"ID"列"Count"的总和,如下所示:

My desired output would be the sum of Column "Count" by "ID" which looks like this:

>head(dfList_agg) [[1]] Count ID 1 3 A 2 3 C [[2]] Count ID 1 3 C 2 1 B

推荐答案

我认为您过于复杂了.试试这个...

I think you've overcomplicated it. Try this...

dfList_agg<-lapply(dfList, function(i) { aggregate(i[,1], by=list(i[,2]), FUN=sum) }) dflist_agg [[1]] Group.1 x 1 A 3 2 C 3 [[2]] Group.1 x 1 B 1 2 C 3

更多推荐

在多个数据框中应用聚合列R

本文发布于:2023-11-22 08:04:03,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1616606.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:多个   框中   数据

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!