Try using tabulate() instead of table(). E.g., compare your original f0 <- function (x, u) { tu <- table(u) indices <- as.numeric(names(tu)) x[indices] <- x[indices] + tu x } to f1 <- function (x, u) { x + tabulate(u, nbins = length(x)) }
I tried it for a 20-long x and 30-long u. f0 and f1 gave identical results. 10^5 iterations of f0 took 62 seconds, f1 1.72 seconds. Bill Dunlap Spotfire, TIBCO Software wdunlap tibco.com > -----Original Message----- > From: r-help-boun...@r-project.org > [mailto:r-help-boun...@r-project.org] On Behalf Of Eric Elguero > Sent: Thursday, February 10, 2011 3:50 AM > To: r-help@r-project.org > Subject: [R] modifynig some elements of a vector > > He everybody, > > I want to add 1 to some elements of a vector: > > x is a vector > u is a vector of idices, that is, integers > assumed to be within the range 1..length(x) > and I want to add 1 to the elements of x > each time their index appears in u > > x[u]<-x[u]+1 works only when there are no > duplicated values in u > > I found this solution: > > tu <- table(u) > indices <- as.numeric(names(tu)) > x[indices] <- x[indices]+tu > > but it looks ugly to me and I would > prefer to avoid calling the function 'table' > since this is to be done millions of times > as part of a simulation program. > > Eric Elguero > Génétique & Adaptation des Plasmodium > IRD > Montpellier - FRance > > ______________________________________________ > R-help@r-project.org mailing list > https://stat.ethz.ch/mailman/listinfo/r-help > PLEASE do read the posting guide > http://www.R-project.org/posting-guide.html > and provide commented, minimal, self-contained, reproducible code. > ______________________________________________ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.