mercredi 10 juin 2020

sum of rows when condition is met- data.frame in R

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(.)
   }
}

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?

EDIT: the result should look like

df
  var1 var2
1 a    4
2 b    2
3 c    6
4 d    88

and analog for df2

Aucun commentaire:

Enregistrer un commentaire