Skip to content
Prev 33043 / 398506 Next

little manipulation on data frame

On Fri, 6 Jun 2003, N Dey wrote:

            
It depends a bit on how many is `many'.

You can get cumulative sums with cumsum, and the first entry in each
column is then

    min(which(cumsum(x) > 10))

The i+1th entry is
    min(which( cumsum(x)-cumsum(x)[-(1:i)] > 10))

If the number of rows is not very large I would do

   sumx<-cumsum(x)
   N1<-min(which(cumsum(x) > 10))
   N1<-c(N1, sapply(1:(length(x)-1), function(i)
		min(which(sumx[-(1:i)]-sumx[i]>10))))

or the equivalent for() loop.

If the number of rows is very large it would be more efficient to rely on
the fact that no more than 10 rows are needed (assuming that zeros aren't
possible)

   n<-length(x)
   sumx<-cumsum(x)

   sumlags<-matrix(nrow=n,ncol=10)
   for(i in 0:9)
	sumlags[,i+1]<-sumx[ c((i+1):n, rep(n,i))]

   N1<-rowSums(sumlags < c(0,sumx[1:(n-1)])+10)+1


	-thomas