Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I satisfy my woes with R's `:` operator?

R's : operator has some well-known 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 by making 1:0 give an empty vector, but I'd prefer it if there were a reasonably terse base or CRAN package that provided such a function (ideally replacing : if that's not too dangerous). I've tried to search for one but can't find it.

Does such a thing exist?

like image 299
Owen Avatar asked Aug 18 '11 21:08

Owen


1 Answers

Try this:

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

Note that seq(1, length = n) works as well.

like image 70
G. Grothendieck Avatar answered Oct 06 '22 00:10

G. Grothendieck