1

I have searched a lot, but not found a solution.

I have the following data frame:

 Age no.observations Factor
1    1               4      A
2    1               3      A
3    1              12      A
4    1               5      B
5    1               9      B
6    1               3      B
7    2              12      A
8    2               3      A
9    2               6      A
10   2               7      B
11   2               9      B
12   2               1      B

I would like to sum create another column with the sum by the categories Age and Factor, thus having 19 for the first three rows, 26 for the next three etc. I want this to be a column added to this data.frame, therefore dplyr and its summarise function do not help.

Tensibai
  • 15,557
  • 1
  • 37
  • 57
Cactus
  • 864
  • 1
  • 17
  • 44
  • See also http://stackoverflow.com/questions/7976001/adding-a-column-of-means-by-group which seem like a more accurate dupe (though using mean instead of sum) – David Arenburg Sep 20 '16 at 12:46

1 Answers1

3

Use mutate with group_by to not summarise:

df %>%
  group_by(Age, Factor) %>%
  mutate(no.observations.in.group = sum(no.observations)) %>%
  ungroup()
AlexR
  • 2,412
  • 16
  • 26
  • Thank you so much for your answer! What do I need the ungroup for? Except for this the code worked perfect for my issue. Thank you. – Cactus Sep 20 '16 at 12:58
  • @rashid It's just a matter of style. Otherwise the result will still be grouped by Age and Factor, wich can lead to unexpected results down the road. – AlexR Sep 20 '16 at 12:59
  • awesome, thank you so much. I have one last question: I am new to stackoverflow and I just tried to use print(df) in R, mark the output and paste this into stackoverflow, but this did not work well and was changed by someone. How do I post a printed data.frame correctly? – Cactus Sep 20 '16 at 13:01
  • There's a Button with curly braces {} for this. Also look at dput for truly copy pasteable output. – AlexR Sep 20 '16 at 13:02
  • Awesome, thank you. – Cactus Sep 20 '16 at 13:10