0
alpha <- c(11,12,21,24,33,11,33)
group <- c("a", "b", "a", "c", "a", "c","d")

df <- data.frame(group,alpha)
df <- df[with(df, order(group)),]

I want to sum the values for each group and append the result in the dataframe but I'm not sure how to do it. The output will be something like the result below.

   group alpha sum
1     a    11  65
2     a    21  65
3     a    33  65
4     b    12  12
5     c    24  35
6     c    11  35
7     d    33  33 
halfer
  • 19,824
  • 17
  • 99
  • 186
Elvis
  • 405
  • 1
  • 4
  • 13

1 Answers1

1

You can use dplyr with group_by to calculate the sum and then join to append your original data.frame:

alpha <- c(11,12,21,24,33,11,33)
group <- c("a", "b", "a", "c", "a", "c","d")

df <- data.frame(group,alpha)
df <- df[with(df, order(group)),]

library(dplyr)
df_stat <- df %>% 
  group_by(group) %>% 
  summarise(sum = sum(alpha))

df <- df %>% 
  left_join(df_stat)

df
  group alpha sum
1     a    11  65
2     a    21  65
3     a    33  65
4     b    12  12
5     c    24  35
6     c    11  35
7     d    33  33
starja
  • 9,887
  • 1
  • 13
  • 28