[prev in list] [next in list] [prev in thread] [next in thread]
List: r-help
Subject: Re: [R] Increment element of vector and efficiency
From: Duncan Murdoch <dmurdoch () pair ! com>
Date: 2003-11-20 15:39:20
[Download RAW message or body]
On Thu, 20 Nov 2003 08:10:38 -0600, Marc Schwartz
<MSchwartz@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
[prev in list] [next in list] [prev in thread] [next in thread]
Configure |
About |
News |
Add a list |
Sponsored by KoreLogic