-3

I have a 10 x 100 matrix and I want to add the first two elements of each column together in R, how do I go about this?

I would like it to be separate for each column, e.g. Column 1 would return the sum of first 2 elements in Column 1, Column 2 would return the sum of first 2 elements in Column 2 etc.

Thank you.

Artem
  • 3,304
  • 3
  • 18
  • 41
  • 1
    you forgot to tag [tag:java], [tag:c#], [tag:c++]... – Adelin Jul 02 '18 at 11:37
  • 1
    Please [edit](https://stackoverflow.com/posts/51135282/edit) your question to include sample data and expected output. Do you want to sum *only the first two* elements in every column, or *every two* elements? What is the dimension of your output `matrix`? Also review how to provide a [minimal reproducible example/attempt](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). – Maurits Evers Jul 02 '18 at 11:41
  • basically I want to create a new matrix (dimension 1x100) from 10x100 matrix but in the new matrix I want the first value to correspond to the sum of the first two elements of column one of the old matrix and so on – john robert Jul 02 '18 at 11:48
  • Not clear! How do you collapse 10 rows of your `10x100` matrix into a single row? If you sum only the first 2 rows, you'll end up with a `9x100` matrix; if you sum entries from *every two rows* per column you get a `5x100` matrix. **Please provide sample data and expected output!** – Maurits Evers Jul 02 '18 at 12:21
  • my matrix x<- matrix(rnorm(1000), nrow=10, ncol=100) and this basically gives me 100 vectors of dimension 10 e.g (x1,x2,x3,...,x10) a hundred times and I need to create a y variable y= x1+x2 for each vector – john robert Jul 02 '18 at 13:31

2 Answers2

0

Use apply for first two rows of your matrix. MARGIN = 2 means apply sum by column.

# create matrix
m <- matrix(rnorm(1000), ncol = 100)

# apply sum to first two rows of the matrix
y <- apply(m[1:2, ], MARGIN = 2, sum)
Artem
  • 3,304
  • 3
  • 18
  • 41
0

You can use the + operator for addition.

If you matrix is called m, then m[1, ] is the first row, m[2, ] is the second row, and m[1, ] + m[2, ] will add the first row to the second row.

Gregor Thomas
  • 136,190
  • 20
  • 167
  • 294