Looking for a function in R to sum rows and cols for matrix reduction

140 views Asked by At

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.

1

There are 1 answers

0
Ishan Juneja On

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]