Re: [R] counting run lengths

2008-10-27 Thread Mario Lavezzi
Dear Richard, Martin, Dimitris and Domenico thank you very much for your help. I must say that the fastest procedure appears to be the one suggested by Richard This runs pretty quickly: unSpells <- nrow(Atr) - apply(Atr,2,function(x) max(which(x==1))) #c(4,0,7,0) If I may abuse of your kin

Re: [R] counting run lengths

2008-10-27 Thread Martin Morgan
Hi Mario -- This function f <- function(m) { ## next 2 lines due to Bill Dunlap ## http://tolstoy.newcastle.edu.au/R/e4/devel/08/04/1206.html csum <- cumsum(!m) crun <- csum - cummax(m * csum) matrix(ifelse(crun > 0, (crun-1) %% nrow(m) + 1, 0), nrow=nrow(m)) } ret

Re: [R] counting run lengths

2008-10-27 Thread Richard . Cotton
> >> It works, but the for (i in ...) loop slows down the simulation a lot. > >> > >> Any suggestion on how to avoid this loop? (or in general, to speed up > >> this part of the simulation) > Actually, I have not specified the following: i want to consider only > the "most recent" sequence of

Re: [R] counting run lengths

2008-10-27 Thread Dimitris Rizopoulos
then try the following: Atr <- cbind(rep(1:0, each = 4), 1, c(1, rep(0, 7)), 1) Atr <- rbind(c(0, 1, 0, 1), Atr) apply(Atr, 2, function (x) { rr <- rle(x) if (tail(rr$values, 1) == 0) tail(rr$length, 1) else 0 }) I hope this what you're looking for. Best, Dimitris Mario Lavezzi wrote

Re: [R] counting run lengths

2008-10-27 Thread Mario Lavezzi
Hi Dimitris, thank you very much. Actually, I have not specified the following: i want to consider only the "most recent" sequence of zeros, that is the last part of the time series. That is, If I have: [,1] [,2] [,3] [,4] [1,]0101 [2,]1111 [3,]11

Re: [R] counting run lengths

2008-10-27 Thread Domenico Vistocco
Try this: unSpells[tail(Atr,1)==0] <- apply(Atr,2,function(x)sum(x==0))[tail(Atr,1)==0] Or (if you don't have to preserve the value in the unSpells vector): unSpells <- apply(Atr,2,function(x)sum(x==0)) But in this case you have 0 instead of 1 in the second and fourth position. Ciao, domenico

Re: [R] counting run lengths

2008-10-27 Thread Dimitris Rizopoulos
it's not totally clear to me what exactly do you need in this case, but have a look at the following: Atr <- cbind(rep(1:0, each = 4), 1, c(1, rep(0, 7)), 1) unSpells <- colSums(Atr == 0) unSpells[unSpells == 0] <- 1 unSpells I hope it helps. Best, Dimitris Mario Lavezzi wrote: Hello, I ha

[R] counting run lengths

2008-10-27 Thread Mario Lavezzi
Hello, I have the following problem. I am running simulations on possible states of a set of agents (1=employed, 0=unemployed). I store these simulated time series in a matrix like the following, where rows indicates time periods, columns the number of agents (4 agents and 8 periods in this