Owen
Owen

Reputation: 39366

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?

Upvotes: 5

Views: 124

Answers (1)

G. Grothendieck
G. Grothendieck

Reputation: 270010

Try this:

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

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

Upvotes: 6

Related Questions