[R] Increment element of vector and efficiency

Duncan Murdoch dmurdoch at pair.com
Thu Nov 20 16:39:20 CET 2003


On Thu, 20 Nov 2003 08:10:38 -0600, Marc Schwartz
<MSchwartz at medanalytics.com> wrote :

>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

If you put these in a big loop, you'll find the second is faster:
both do the indexing twice, but the second also has an extra couple of
function calls.

> system.time(for (i in 1:10000) increment(x[3]))
[1]   NA   NA 1.44   NA   NA
> system.time(for (i in 1:10000) x[3] <- x[3]+1)
[1]   NA   NA 0.52   NA   NA

Duncan Murdoch




More information about the R-help mailing list