R DPLYR Rowwise SUM

I have

DATA = data.frame(GROUP = c(1,2,1,2,1,2), TIME = c(1,1,2,2,3,3), SCORE = c(0,7,9,8,3,4))

and seek to create

WANT = data.frame(GROUP = c(1,2,3,1,2,3,1,2,3), TIME = c(1,1,1,2,2,2,3,3,3), SCORE = c(0,7,7,9,8,17,3,4,7))

Where for each value of TIME I sum up the SCORE values for all GROUP

I try without success,

WANT = DATA %>% group_by(TIME) %>% rowwise() %>% mutate(`3' = sum())

>Solution :

I suggest summarize the data and then combine (bind_rows) with the original data.

library(dplyr)
DATA %>%
  group_by(TIME) %>%
  summarize(GROUP = max(GROUP)+1, SCORE = sum(SCORE)) %>%
  bind_rows(DATA, .) %>%
  arrange(TIME, GROUP)
#   GROUP TIME SCORE
# 1     1    1     0
# 2     2    1     7
# 3     3    1     7
# 4     1    2     9
# 5     2    2     8
# 6     3    2    17
# 7     1    3     3
# 8     2    3     4
# 9     3    3     7

Leave a Reply