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
I think that's about as efficient as you can get. I'm not sure of the underlying details. There was some discussion recently of having the equivalent of a "+=" operator but currently R has no such thing. -roger 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 > > ______________________________________________ > R-help at stat.math.ethz.ch mailing list > https://www.stat.math.ethz.ch/mailman/listinfo/r-help >
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? > > PascalThere 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 ofcourse:> 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