How can I satisfy my problems with the R `:` operator?

Operator

R :has some famous gotchas:

a = c(1, 2, 3)
set.zero = function(n) a[1:n] <<- 0
set.zero(0)
# `a` is now c(0, 2, 3)

I could just write a function that solves this, forcing 1:0to give an empty vector, but I would prefer if there were a sufficiently thin baseor CRAN package that provided such a function (ideally replacing :if it is not so dangerous). I tried to find him, but I can not find him.

Is there such a thing?

+5
source share
1 answer

Try the following:

set.zero = function(n) a[seq_len(n)] <<- 0

Please note that seq(1, length = n)also works.

+6
source

All Articles