Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to add column reporting sum of couple of subsequent rows

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

This should do:

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

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading