rgroup-byrowsum

Adding values of two rows and storing them in another column with repetition


I have a data frame like this

x1<- c(0,1,1,1,1,0)

df<-data.frame(x1)

I want to add another column that will take the sum of every two rows and store the value for the first two rows. This should look like this.

enter image description here

You can see here that the first two rows' sum is 1 and that is given in the first two rows of the new column (x2). Next, the third and fourth-row sum is given in the 3rd and fourth row of the new column. Can anyone help?


Solution

  • You can define the groups using floor division and then simply obtain the grouped sum:

    library(dplyr)
    
    df %>%
      mutate(group = (row_number() - 1) %/% 2) %>%
      group_by(group) %>%
      mutate(x2 = sum(x1)) %>%
      ungroup() %>%
      select(-group)
    # # A tibble: 6 × 2
    #      x1    x2
    #   <dbl> <dbl>
    # 1     0     1
    # 2     1     1
    # 3     1     2
    # 4     1     2
    # 5     1     1
    # 6     0     1