Matrix operation in R


#1
Can we have for loop or other thing for solving the following matrix?
matrix A (given 6x6)

a 1 5 6 9 5 8
b 8 6 2 4 7 9
c 9 5 1 7 5 3 
d 2 5 6 3 4 1 
e 7 4 2 3 6 5 
f 1 5 3 7 8 9 

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

I have a large maxtrix of 4519x4519, therefore looking for a for loop


#2

If I understand you problem correctly, you want to add a column (ie. col i) with the next (ie. col i+1). You can do that, I think efficiently, using vectorisation and subseting,

  • by creating two matrices from the starting one : One with odd columns indices and other with even columns indices
  • add them together, term by term.
mat <- matrix(c(1,5,6,9,5,8,8,6,2,4,7,9,9,5,1,7,5,3,2,5,6,3,4,1,7,4,2,3,6,5,1,5,3,7,8,9), 
       nrow = 6, ncol = 6, byrow = TRUE)
mat
#>      [,1] [,2] [,3] [,4] [,5] [,6]
#> [1,]    1    5    6    9    5    8
#> [2,]    8    6    2    4    7    9
#> [3,]    9    5    1    7    5    3
#> [4,]    2    5    6    3    4    1
#> [5,]    7    4    2    3    6    5
#> [6,]    1    5    3    7    8    9

# find odd and even column indices
odd_col <- as.logical(seq_len(ncol(mat)) %% 2)
even_col <- !odd_col 
# add together the two matrices : One with only the odd col (1, 3, 5) with even col (2, 4, 6)
mat[, odd_col] + mat[, even_col]
#>      [,1] [,2] [,3]
#> [1,]    6   15   13
#> [2,]   14    6   16
#> [3,]   14    8    8
#> [4,]    7    9    5
#> [5,]   11    5   11
#> [6,]    6   10   17

Created on 2018-08-13 by the reprex package (v0.2.0).

This is the result you are looking for.

However, you full matrix has an odd column number (4519), so the two matrices won't have the same size (2160 and 2159) and won't add up...
So I may have misunderstood the issue.


#3

Dear Sir,

In actual dataset I have 1500 plus matrices and each matrix has 4519 x 4519 size.
I was looking for adding column no. from 1 to 6, then 7 to 12, 13 to 18 and so on.
Therefore, looking for a help on for loop or user defined function to do it. It is not adding even or odd columns.

It would be great if you can help me on how to add columns as I mentioned above.

Thank you


#4

Sorry, but I am not sure to see what you want to achieve. On you example above, you have a 6 col matrix and you add col 1 + col 2, col3 + col4 and col5+col6. So odd and even.
Can you be more precise or provide another example using a 12 col matrix ?