lundi 15 juin 2020

sum of all rows when specific column is equal -data.frame in R

df
  var1 var2  var3
1    a    1  0.5
2    b    2  5
3    a    3  12
4    c    6  0
5    d   88  0
6    b    0  0

df2
  var1 var2  var3
1  k    1    0.5
2  l    0.6  5
3  k    3    12
4  k    6    0
5  v   12    0


> list <- list(df,df2)

for(i in list){
   i %>% 
  group_by(var1) %>% 
  summarise(sum = sum(var1))
}

Whenever var1 is equal, I want the rest of the rows to be summed up, and this would be the new row. I want that the list of data.frames only contains data.frames that have unique rows, but the columns should add up. I have the loop from here sum of rows when condition is met- data.frame in R , but I was not statisfied with the answers.

The result should look like this

df
  var1 var2  var3
1    a    4  12.5
2    b    2  5
4    c    6  0
5    d   88  0

df2
  var1 var2  var3
1  k    10    12.5
2  l    0.6  5
3  v   12    0

my real list contains a lot data.frames with a lot of rows and columns. Thank you

Aucun commentaire:

Enregistrer un commentaire