Grec001
Grec001

Reputation: 1121

How to get a specific column from a matrix in r?

I have a matrix as following, how can I extract the desired column with [

MX <- matrix(101:112,ncol=3)
MX[,2]
# [1] 105 106 107 108
`[`(MX, c(1:4,2))
# [1] 101 102 103 104 102

Obviously, it does not extract 2nd column as intuitive guess, but honestly gets the 2nd element of all.

More like I am asking how to express MX[,2] with [.

Please advise, Thanks

Upvotes: 2

Views: 58

Answers (1)

akrun
akrun

Reputation: 887108

Keep the row index as blank

`[`(MX, ,2)
#[1] 105 106 107 108

or if we need to extract selected rows (1:4) of a specific column (2), specify the row, column index without concatenating. c will turn the row and column index to a single vector instead of two

`[`(MX, 1:4, 2)
#[1] 105 106 107 108

Upvotes: 2

Related Questions