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]
                : 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
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With