How to sum values from columns of a matrix into a vector tha concatenates sum of each column? (Without using For)

I have a homework to do and my professor won't let me use the command For in it, someone can help me?

Try using the function colSums, which is in base R - you don't need to install any package to use it.

2 Likes

forgive my inexperience, I think I wrote what I want to do in a wrong way. I want to sum the values of the first and second row of a matrix and get a vector as output, and each value of the vector is the sum of the column 1 of these two lines, and after column 2, and goes on. maybe rowsum can help me?

Oh, I got it now, colSums does help me with that, but I'm trying to find way to stop it at row 2

Can you use the matrix below to give an example of what you're trying to calculate? I want to make sure that I understand what you're asking.

> m <- matrix(1:9, nrow = 3)
> m
     [,1] [,2] [,3]
[1,]    1    4    7
[2,]    2    5    8
[3,]    3    6    9

Yes, using this matrix I would like to sum the values of the first and second row and get as a result the vector:

vector
3 9 15

You can definitely use colSums to do this. You need to think about how you can select just the first two rows of a matrix - you can apply colSums to the result.

1 Like

I got it now, thank you for helping.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.