[R] Increment element of vector and efficiency

Marc Schwartz MSchwartz at medanalytics.com
Thu Nov 20 15:10:38 CET 2003


On Thu, 2003-11-20 at 07:43, Pascal A. Niklaus wrote:
> Hi all,
> 
> Thanks for the incredibly quick help with the "%in%"...
> 
> There's a second question, though: I'd like to increment an element of a 
> vector if a certain event occurs, e.g.
> 
>     count[event] <- count[event] + 1;         # works, but...
> 
> Is this efficient? I wonder whether R needs to subset the count vector 
> on both sides of the assignment operator (i.e., twice), or whether 
> there's a shortcut like "++" in C, e.g. "count[i]++" or similar?
> 
> Pascal


There is no increment operator in R. However, it would not be difficult
to create a function to increment a value:

increment <- function(x)
{
  eval.parent(substitute(x <- x + 1))
}

> x <- c(2, 5, 3, 8)
> increment(x[3])
> x
[1] 2 5 4 8
> increment(x[3])
> x
[1] 2 5 5 8
> increment(x[3])
> x
[1] 2 5 6 8

>From a practical standpoint however, it does not save any time of
course:

> system.time(increment(x[3]))
[1] 0 0 0 0 0
> system.time(x[3] <- x[3] + 1)
[1] 0 0 0 0 0


HTH,

Marc Schwartz




More information about the R-help mailing list