Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

select submatrix in R

Tags:

r

matrix

I have a matrix called m as follows

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

I want to remove the first column of this matrix. Within a function I pass a value called j, which is always 1 less than the number of columns in m (In this example j is 4). Therefore I used the following code

 >m[,2:4+1]
     [,1] [,2] [,3]
[1,]    7   10   13
[2,]    8   11   14
[3,]    9   12   15

But it is giving only the last 3 columns. Then I changed the code as follows

 >m[,2:(4+1)]

This time I had the correct output. Also it is giving the same output for following code as well

> m[,1:4+1]

Somebody please explain me how the following codes work?

>m[,2:4+1]
>m[,1:4+1]
like image 572
Chesmi Kumbalatara Avatar asked Dec 20 '22 22:12

Chesmi Kumbalatara


1 Answers

: has higher precedence than +, therefore 2:4+1 gets interpreted at (2:4)+1 which is the same as 3:5:

2:4+1
[1] 3 4 5

Similarly, 1:4+1 gets interpreted as 2:5:

1:4+1
[1] 2 3 4 5

To remove columns in a matrix, its probably easier to use the negative subscript input to [:

m[,-1]
     [,1] [,2] [,3] [,4]
[1,]    4    7   10   13
[2,]    5    8   11   14
[3,]    6    9   12   15
like image 72
James Avatar answered Jan 31 '23 10:01

James