Basic question related to Indexing from a newbie

newvariable <- newvector[2:11-1]
newvariable
[1] 3.0 4.0 5.0 6.0 2.0 -5.1 -33.0 2.0 -5.1 -33.0
newvariable <- newvector[2:(11-1)]
newvariable
[1] 4.0 5.0 6.0 2.0 -5.1 -33.0 2.0 -5.1 -33.0

Can you please tell me why there is a difference in output from these two?

Hi, and welcome!

This isn't quite a reproducible example, called a reprex because we don't have newvector. It's generally a good idea to include a reprex to attract more and better answers.

In this case, however, it's easy enough to replicate the situation.


## Annette Dobson (1990) "An Introduction to Generalized Linear Models".
## Page 9: Plant Weight Data.
newvector <- c(4.17,5.58,5.18,6.11,4.50,4.61,5.17,4.53,5.33,5.14)
## how long is newvector?
length(newvector)
#> [1] 10
## what is the second element of newvector?
newvector[2]
#> [1] 5.58
## what is the tenth (11-1) element?
newvector[10]
#> [1] 5.14
## what are the second to tenth elements of newvector?
newvector[2:10]
#> [1] 5.58 5.18 6.11 4.50 4.61 5.17 4.53 5.33 5.14
## assign the second to tenth elements of newvector to newvariable
newvariable <- newvector[2:11-1]
newvariable
#>  [1] 4.17 5.58 5.18 6.11 4.50 4.61 5.17 4.53 5.33 5.14
## how long is newvariable?
length(newvariable)
#> [1] 10
## is it identical to newvector[1:10]?
newvariable == newvector[1:10]
#>  [1] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
## what is in newvector[2:(11-1)]
newvector[2:(11-1)]
#> [1] 5.58 5.18 6.11 4.50 4.61 5.17 4.53 5.33 5.14
## how long is it?
length(newvector[2:(11-1)])
#> [1] 9

Created on 2020-01-12 by the reprex package (v0.3.0)

To continue from the illustration by Richard, the difference between 2:11-1 and 2:(11-1) is that the first one gets evaluated to 1:10, and the second one gets evaluated to 2:10.

This happens because sequence operator : has precedence over binary substract operator -. In first case, the sequence 2:11 is evaluated first, and then 1 is subtracted from each element of that sequence. For the second case, parentheses takes precedence to calculate 11-1 first, and then 2:10 gets evaluated.

The precedence of operations are documented here:

https://stat.ethz.ch/R-manual/R-devel/library/base/html/Syntax.html

Hope this helps.

3 Likes

Thanks a lot for explaining.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.