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
CodePudding user response:
We may also use rowSums
after converting into a 3 column matrix
rowSums(matrix(`length<-`(sample, nrow(sample) nrow(sample) %% 3 -1),
byrow = TRUE, ncol = 3), na.rm = TRUE)
[1] 6 15 24 13 12 21 19