Home > Back-end >  How to add column reporting sum of couple of subsequent rows
How to add column reporting sum of couple of subsequent rows

Time:09-26

I have the following dataset

structure(list(Var1 = structure(c(1L, 2L, 1L, 2L, 1L, 2L, 1L, 
2L), .Label = c("0", "1"), class = "factor"), Var2 = structure(c(1L, 
1L, 2L, 2L, 1L, 1L, 2L, 2L), .Label = c("congruent", "incongruent"
), class = "factor"), Var3 = structure(c(1L, 1L, 1L, 1L, 2L, 
2L, 2L, 2L), .Label = c("spoken", "written"), class = "factor"), 
    Freq = c(8L, 2L, 10L, 2L, 10L, 2L, 10L, 2L)), class = "data.frame", row.names = c(NA, 
-8L))

I would like to add another column reporting sum of coupled subsequent rows. Thus the final result would look like this:

enter image description here

I have proceeded like this

Table = as.data.frame(table(data_1$unimodal,data_1$cong_cond, data_1$presentation_mode)) %>% 
  mutate(Var1 = factor(Var1, levels = c('0', '1'))) 


row = Table %>%  #is.factor(Table$Var1)
  summarise(across(where(is.numeric),
                   ~ .[Var1 == '0']    .[Var1 == '1'],
                   .names = "{.col}_sum"))

column = c(rbind(row$Freq_sum,rep(NA, 4)))
Table$column = column

But I am looking for the quickest way possible with no scripting separated codes. Here I have used the dplyr package, but if you might know possibly suggest some other ways with map(), for loop, and or the method you deem as the best, please just let me know.

CodePudding user response:

This should do:

df$column <- 
  rep(colSums(matrix(df$Freq, 2)), each=2) * c(1, NA)

CodePudding user response:

If you are fine with no NAs in the dataframe, you can

df %>% 
  group_by(Var2, Var3) %>% 
  mutate(column = sum(Freq))

# A tibble: 8 × 5
# Groups:   Var2, Var3 [4]
  Var1  Var2        Var3     Freq column
  <fct> <fct>       <fct>   <int>  <int>
1 0     congruent   spoken      8     10
2 1     congruent   spoken      2     10
3 0     incongruent spoken     10     12
4 1     incongruent spoken      2     12
5 0     congruent   written    10     12
6 1     congruent   written     2     12
7 0     incongruent written    10     12
8 1     incongruent written     2     12
  • Related