Wednesday 8 July 2015

R Subsetting matrices


You can get the elements of matrix using subsetting feature.

> x <- matrix(1:12, 3, 4)
> x
     [,1] [,2] [,3] [,4]
[1,]    1    4    7   10
[2,]    2    5    8   11
[3,]    3    6    9   12
> 
> x[1,1]
[1] 1
> x[2,4]
[1] 11
> 
> 
> x[1, ]
[1]  1  4  7 10
> 
> x[, 4]
[1] 10 11 12

x[1,1] : Returns elements at 1st row and 1st column.
x[2,4] : Returns element at 2nd row and 4th column.
x[1, ] : Return 1st row
x[, 4] : Return 4th column


If a single matrix element returned, it returns element as a vector, not as matrix. You can turn off this default behavior, by passing extra argument drop=FALSE.

> x[1,2]
[1] 4
> x[1,2, drop=FALSE]
     [,1]
[1,]    4

x[1, ]
x[, 1]

Even in the above cases also, you won't get a matrix. Use drop parameter to get matrix as result.

> x[1,]
[1]  1  4  7 10
> x[,1]
[1] 1 2 3
> 
> x[1,,drop=FALSE]
     [,1] [,2] [,3] [,4]
[1,]    1    4    7   10
> 
> x[,1,drop=FALSE]
     [,1]
[1,]    1
[2,]    2
[3,]    3
>





Prevoius                                                 Next                                                 Home

No comments:

Post a Comment