1
$\begingroup$

Let's say I have a dataset like thisX<-matrix(rnorm(30), nrow=100, ncol=6). I am trying to find a way to apply the sum function to every four rows of column 3. This means I want to sum rows 1-4, rows 4-8 and so on.

Are there any functions such as apply or lapply I could use?

$\endgroup$
2
$\begingroup$

You could use tapply or aggregate:

set.seed(1)
X <- matrix(rnorm(30), nrow=100, ncol=6)
id <- ceiling(seq_len(nrow(X))/4)

tapply(X[, 3], id, sum)
#       1       2       3       4       5       6       7       8       9      10 
# -0.2137 -1.0629 -0.5030  0.2687  1.4961 -0.9343  2.0076  3.1162 -1.3511 -1.6868

aggregate(X[, 3], by=list(id), FUN=sum)
#    Group.1       x
# 1        1 -0.2137
# 2        2 -1.0629
# 3        3 -0.5030
# 4        4  0.2687
# 5        5  1.4961
# 6        6 -0.9343
# 7        7  2.0076
# 8        8  3.1162
# ...

# check results
sum(X[1:4, 3])
# [1] -0.2137
sum(X[5:8, 3])
# [1] -1.063
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.