Create a new matrix in R by adding the rows of another matrix

So, I have the following matrix (let its output be called):

> output [,1] [,2] [,3] [,4] [,5] [,6] [1,] 1 1 1 0 0 1 [2,] 1 1 1 0 0 1 [3,] 1 1 1 0 0 1 [4,] 0 0 0 0 0 0 [5,] 1 0 1 1 0 0 [6,] 1 0 1 1 0 0 

What I want to do is create a new matrix (output2) by adding rows to two groups. For example, the first row of the new matrix will be as follows:

 output2[1,] <- output[1,] + output[2,] 

The second row of the new output matrix file will consist of the sum of the third and fourth rows of the old output matrix:

 output2[2,] <- output[3,] + output[4,] 

And so on. I was wondering how best to encode this, given that I would need to do the same with large matrices. I considered creating dummy variables using the seq () function and possibly a for loop.

Is there an easier way?

Edit:

dput (exit)

(c (1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 0 , 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0 , 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1 , 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0 , 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0 , 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1 , 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 0, 0 , 0, 0, 0, 1, 0, 0, 0, 0, 0, 0), Dim = c (10L, 19L))

+5
source share
3 answers

If m is your matrix, try the following:

 m[seq(1,by=2,to=nrow(m)),]+m[seq(2,by=2,to=nrow(m)),] 
+1
source

These are both:

  • handles both odd and even line numbers
  • generalize to k lines, replacing 2 by k
  • are short - one line of code or can easily be done in one line
  • (1) uses only basic functions, i.e. no packages and (2) can be easily generalized to functions other than the sum.

1) rowsum Use rowsum with the second argument c(1, 1, 2, 2, ..., 5, 5) , which is easily created with gl :

 nr <- nrow(output) rowsum(output, gl(nr, 2, nr)) 

2) rollapply Another possibility is to use rollapply from the zoo. If we knew that the number of lines was even, we could optionally omit alignment and partial arguments.

 library(zoo) rollapply(output, 2, by = 2, sum, align = "left", partial = TRUE) 
+1
source

Another option is to use vector recycling:

 matrix(output[c(TRUE, FALSE)] + output[c(FALSE, TRUE)], ncol = ncol(output)) 
+1
source

Source: https://habr.com/ru/post/1273685/


All Articles