2
 [Can we have a for loop or other thing for solving the following matrix?
 Matrix A (given 6 x 16)
 a 1 5 6 9 5 8 5 6 7 9 4 6 2 5 4 6
 b 8 6 2 4 7 9 2 3 4 8 6 2 1 6 8 2
 c 9 5 1 7 5 3 7 5 3 9 5 1 2 6 9 3
 d 2 5 6 3 4 1 8 4 2 6 9 5 1 3 7 1
 e 7 4 2 3 6 5 7 4 1 2 3 6 9 8 5 2 
 f 1 5 3 7 8 9 4 6 3 1 5 2 8 9 5 4  

 Output (6 x 4)
 a 1+5+6+9 5+8+5+6 7+9+4+6 2+5+4+6
 b 8+6+2+4 7+9+2+3 4+8+6+2 1+6+8+2
 c 9+5+1+7 5+3+7+5 3+9+5+1 2+6+9+3
 d 2+5+6+3 4+1+8+4 2+6+9+5 1+3+7+1
 e 7+4+2+3 6+5+7+4 1+2+3+6 9+8+5+2
 f 1+5+3+7 8+9+4+6 3+1+5+2 8+9+5+4

 I have a large maxtrix of 4519 x 4519, therefore looking for a for loop.]

 matb <- matrix(data = 0, nrow =6 ,ncol = 6)
    for (a in 1: nrow (data)) {
      for (b in 1:seq (1,5,by=2)) {
          c <- b+1
           matb [a,1:3] <- rbind (sum(data[a,b:c]))


    }  
 }

I tried using above syntax, but it did not work. Therefore, looking for help on for loop or function to solve this problem.

Litesh
  • 21
  • 3

1 Answers1

1

We can use recycling to select alternating columns, then add:

# example matrix
m <- matrix(1:12, ncol = 4)
#      [,1] [,2] [,3] [,4]
# [1,]    1    4    7   10
# [2,]    2    5    8   11
# [3,]    3    6    9   12

m[, c(TRUE, FALSE)] + m[, c(FALSE, TRUE)]
#       [,1] [,2]
# [1,]    5   17
# [2,]    7   19
# [3,]    9   21
zx8754
  • 52,746
  • 12
  • 114
  • 209
  • sir it worked out for the given dataset, but the problem in hand is I have to add column 1:4, then 5:8, 9:12 and so on. – Litesh Aug 13 '18 at 09:21
  • @Litesh Then you should post example data that represents your actual data. I am closing as duplicate, see linked post. – zx8754 Aug 13 '18 at 09:21