Tony Chen
Tony Chen

Reputation: 19

How to extracting consecutive columns from a matrix in R?

I'm new to R and I have experience in Matlab. When using matrix in R, I found it really inconvienent.

How to extracting consecutive columns from a matrix in R?

I already know that I can use tail() and head() to extracting consecutive rows.

For example

     [,1] [,2] [,3] [,4]
[1,]    1    4    7    0
[2,]    2    5    8    1
[3,]    3    6    9    2

use tail(a,-1) I can get the last two rows, but what if I want to get the first two columns?

Thanks

Upvotes: 0

Views: 459

Answers (2)

user13985
user13985

Reputation: 221

First column

a[, 1]

First two columns

a[, 1:2]  

First 10 columns

a[, 1:10]

And so on.

Upvotes: 3

germcd
germcd

Reputation: 944

you can get the first two columns using

a[,1:2]

or

a[,c(1,2)] 

Upvotes: 5

Related Questions