-4

Looking for a R function to sum rows and columns.

I have a matrix (6x6). I want to sum [1,1]+[1,2]+[2,1]+[2,2], and then the same for the rest of the matrix, finally I want to get a 3x3 matrix, in which each [i,j] as the respective sum.

Jason Aller
  • 3,541
  • 28
  • 38
  • 38
  • 2
    The question doesn't appear to include any attempt at all to solve the problem. Please edit the question to show what you've tried, and show a specific roadblock you're running into with [Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve). For more information, please see [How to Ask](https://stackoverflow.com/help/how-to-ask). – Andreas Nov 06 '19 at 05:42
  • Thanks for yours comments.It's my first time in this forum. Actually is hard to explain the question, but i try again. I need a R function to reduce the dimension of a matrices. For example in a 6x6 matrix , i want to sum rows and col to obtain a 3x3 matrix, in wich each cell is the sum of 4 cell for the first matrxi. The first cell in 3x3 matrix must be sum of the first [1,1]+[1,2]+[2,1]+[2,2], the second cell in the row must be [1,3]+[1,4]+[2,3]+[2,4], the next cell on the cols must be [3,1]+[4,1]+[3,2]+[4,2], same algorithm for the next cell, and so on. – Pablo Andres Gonzalez Sanchez Nov 07 '19 at 12:34

1 Answers1

0

You can try something like this:

#define matrix with no. of columns and rows    
m<-matrix(1:6,nrow = 6,ncol = 6)

m_req<-m

for(i in 1:nrow(m_req)){
  if(i!=nrow(m_req)){
    m_req[i,]<-m_req[i,]+m_req[i+1,]
    m_req[,i]<-m_req[,i]+m_req[,i+1]
  }
}

req_columns<-seq(1,ncol(m_req),by=2)

m_req<-m_req[req_columns,req_columns]
Ishan Juneja
  • 401
  • 4
  • 11