I just discovered that `[<-`
may have destructive side-effects or not depending on what arguments one gives it.
Example
x <- 1:5
x
# [1] 1 2 3 4 5
`[<-`(x, 1:5, 1)
# [1] 1 1 1 1 1
x
# [1] 1 2 3 4 5 # ∴ last application of `[<-` was non-destructive
`[<-`(x, 1:5, TRUE)
# [1] 1 1 1 1 1
x
# [1] 1 1 1 1 1 # ∴ the last application of `[<-` had a destructive side-effect
Q: Is there a general way to reliably prevent the destructive behavior, or at least guard against it? (Short, of course, of avoiding `[<-`
altogether.)
Notes
I was not able to find the answer to my question in the documentation (
?`[<-`
); in general, I had a hell of a time finding any official documentation on (?`...<-`
)-type "replacement" operators (I don't even know what they're called), and none that addresses head-on the question of side-effects.Of course, for all I know, even the behavior I've labeled "non-destructive" may still have some other side-effects I'm not aware of.
For the simple example above, the expression
as.logical(`[<-`(x, 1:5, 1))
has the same value as as that of`[<-`(x, 1:5, TRUE)
, and retains the same one-line functionality, but has no (obvious) side-effects. This alternative, however, is not a general solution to this problem.
Update (in response to BrodieG's request)
$ R --quiet --no-save --no-restore
> x <- 1:5
> x
[1] 1 2 3 4 5
> `[<-`(x, 1:5, TRUE)
[1] 1 1 1 1 1
> x
[1] 1 1 1 1 1
> sessionInfo()
R version 3.3.1 (2016-06-21)
Platform: x86_64-pc-linux-gnu (64-bit)
Running under: Debian GNU/Linux 8 (jessie)
locale:
[1] LC_CTYPE=en_US.utf8 LC_NUMERIC=C
[3] LC_TIME=en_US.utf8 LC_COLLATE=en_US.utf8
[5] LC_MONETARY=en_US.utf8 LC_MESSAGES=en_US.utf8
[7] LC_PAPER=en_US.utf8 LC_NAME=C
[9] LC_ADDRESS=C LC_TELEPHONE=C
[11] LC_MEASUREMENT=en_US.utf8 LC_IDENTIFICATION=C
attached base packages:
[1] stats graphics grDevices utils datasets methods base