How can the "["
function be used to select a column or a row of a matrix?
x <- matrix(1:4, ncol=2)
As far as I understand, these two lines do the same thing:
x[1,2]
"["(x,1,2)
Also these two:
x[4]
"["(x,4)
But how can one rewrite
x[2,]
using "["(...) ?
To get a specific column of a matrix, specify the column number preceded by a comma, in square brackets, after the matrix variable name. This expression returns the required row as a vector.
Similar to vectors, you can use the square brackets [ ] to select one or multiple elements from a matrix. Whereas vectors have one dimension, matrices have two dimensions. You should therefore use a comma to separate the rows you want to select from the columns.
Just leave the argument blank
"["(x, 2, ) # second row
[1] 2 4
"["(x, ,2) # second column
[1] 3 4
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With