本文介绍了在多个数据框中应用聚合列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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-09 01:36