[R] Increment element of vector and efficiency
Marc Schwartz
MSchwartz at medanalytics.com
Thu Nov 20 17:08:56 CET 2003
On Thu, 2003-11-20 at 09:39, Duncan Murdoch wrote:
> 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
Good point Duncan. The function call approach does introduce some
overhead.
It has been a while (years) since I have done any serious C coding, but
if my 45 year old memory is not failing me, my recollection is that the
advantage of the C increment operators (besides the fact that C is
compiled and R is interpreted), is that they compiled "one to one" with
machine level integer addition instructions, which made them faster and
more efficient. On the x86 family I believe it was INC.
Of course, the end result is also likely to be dependent upon compiler
optimization options as well.
Thanks,
Marc
More information about the R-help
mailing list