条件满足时的行总和-R中的data.frame [英] sum of rows when condition is met- data.frame in R
本文介绍了条件满足时的行总和-R中的data.frame的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
df
var1 var2
1 a 1
2 b 2
3 a 3
4 c 6
5 d 88
6 b 0
df2 <- data.frame(var1=c("k","b","a","k","k","b"),var2=c(14,78,5,6,88,0))
> list <- list(df,df2)
for(i in list){
if(any(i[ ,1] == i[ ,1})){
cumsum(.)
}
}
我有一个包含data.frames的列表.我想遍历这些data.frames.如果第一列中有相同的字母,则应计算总和.我希望此新行在我的data.frame中.
我完全搞砸了if statement
.有人可以帮我吗?
I have a list containing of data.frames. I want to iterate over these data.frames. When there is the same letter in the first column, then the sum should be calculated. I want this new row to be in my data.frame.
I completely messed up the if statement
. Can somebody help me please?
结果应类似于
df
var1 var2
1 a 4
2 b 2
3 c 6
4 d 88
以及df2
var1 var2
1 k 108
2 b 78
3 a 5
在我真正的问题中,列表由10个data.frames组成,而不仅仅是两个
In my real problem, the list consists of 10 data.frames, not just two
推荐答案
在Base-R中
sapply(split(df$var2,df$var1), sum)
a b c d
4 2 6 88
或在数据框列表的每个元素上执行
or to do it on each element of a list of dataframes
lapply(list, function(x) sapply(split(x$var2,x$var1), sum))
[[1]]
a b c d
4 2 6 88
[[2]]
a b k
5 78 108
这篇关于条件满足时的行总和-R中的data.frame的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文