I noticed the following when using '[<-'
. I am successful at replacing elements but not at appending an element to the vector.
Example:
VarX <- integer()
VarX[1] <- 11
`[<-`(VarX, 2, 22)
VarX
# [1] 11
# Expected the value of VarX to be:
# [1] 11 22
# Also tried:
`[<-`(VarX, i=2, value=22)
VarX
# [1] 11
However, if there is already a value at the index, the value does get replaced.
VarX <- integer()
VarX[1] <- 11
VarX[2] <- 99
VarX
# [1] 11 99
`[<-`(VarX, 2, 22)
VarX
# [1] 11 22
Do I simply have the syntax wrong, or is this as intended? Any further insight into what is going on here would be appreciated.
Please note, there is no concrete objective here other than to better understand the language.
Update regarding @Roland and @Dason 's comments.
It appears that the behavior is tied to how the values of the object are initially assigned. For example, when the value assigned to VarX
is 1:2
versus c(1, 2)
the behavior of [<-
(VarX, 2, 22)
gives different results, as shown below:
### changes not saved to VarX
rm(VarX) # actually ran: rm(list=ls(all=TRUE))
VarX <- 1:2
VarX
# [1] 1 2
`[<-`(VarX, 2, 22)
# [1] 1 22
VarX
# [1] 1 2
### changes ARE saved to VarX
rm(VarX) # actually ran: rm(list=ls(all=TRUE))
VarX <- c(1, 2)
VarX[2] <- 2
VarX
# [1] 1 2
`[<-`(VarX, 2, 22)
# [1] 1 22
VarX
# [1] 1 22
> sessionInfo()
R version 2.15.1 (2012-06-22)
Platform: x86_64-apple-darwin9.8.0/x86_64 (64-bit)
locale:
[1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8
attached base packages:
[1] stats graphics grDevices utils datasets methods base