Home > OS >  How to use R language to solve the sum of every three rows of a matrix?
How to use R language to solve the sum of every three rows of a matrix?

Time:06-19

How to find the sum of every three rows of the following matrix using R?

sample <- matrix(rep(1:10,times = 2),nrow = 20 , ncol = 1)
sample

CodePudding user response:

rowsum(sample, gl(nrow(sample),3,nrow(sample)))
  [,1]
1    6
2   15
3   24
4   13
5   12
6   21
7   19

or even:

tapply(sample, rep(seq(nrow(sample)),each = 3,length = nrow(sample)), sum)
 1  2  3  4  5  6  7 
 6 15 24 13 12 21 19 

tapply(sample, as.numeric(gl(nrow(sample),3,nrow(sample))), sum)
 1  2  3  4  5  6  7 
 6 15 24 13 12 21 19 

tapply(sample, droplevels(gl(nrow(sample),3,nrow(sample))), sum)
 1  2  3  4  5  6  7 
 6 15 24 13 12 21 19 

CodePudding user response:

Here is a dplyr approach:

library(dplyr)

my_sums3 <- data.frame(sample) %>% 
  group_by(group= ceiling(row_number()/3)) %>%  
  summarise(sum = sum(sample), .groups = "drop_last") %>% 
  dplyr::select(-group) %>% 
  as.matrix()
     sum
[1,]   6
[2,]  15
[3,]  24
[4,]  13
[5,]  12
[6,]  21
[7,]  19
  •  Tags:  
  • r
  • Related