Select sub-matrix in R

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. Inside the function, the value j is transferred, which is always 1 less than the number of columns in m (in this example, j is 4). So 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 gives only the last 3 columns. Then I changed the code as follows:

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

This time I had the right conclusion. It also gives the same result for the following code, as well

> m[,1:4+1]

Someone please explain to me how the following codes work?

>m[,2:4+1]
>m[,1:4+1]
+4
source share
1 answer

:has a higher priority than +, therefore, is 2:4+1interpreted in (2:4)+1, which matches 3:5:

2:4+1
[1] 3 4 5

, 1:4+1 2:5:

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

, , [:

m[,-1]
     [,1] [,2] [,3] [,4]
[1,]    4    7   10   13
[2,]    5    8   11   14
[3,]    6    9   12   15
+11

All Articles