Counting column data in a matrix with resets
r
Solution
This should work. Note that each of your cats is an independent individual so you can turn your data frame into a list and use `mclapply` which uses a paralleled approach.
count <- function(y,x){
if(is.na(x)) return(0)
return (y + 1)
}
oneCat = m[,1]
Reduce(count,oneCat,init=0,accumulate=TRUE)[-1]
EDIT: here is the full answer
count <- function(x,y){
if(is.na(y)) return(0)
return (x + 1)
}
mclapply(as.data.frame(m),Reduce,f=count,init=0,accumulate=TRUE)
EDIT2: The main bad problem is that I do get extra 0's at the beginning so...
result = mclapply(as.data.frame(m),Reduce,f=count,init=0,accumulate=TRUE)
finalResult = do.call('cbind',result)[-1,]
rownames(finalResult) = rownames(m)
does the job.
Problem
I'm gathering data on how much my cats poop into a matrix: ``` m <- cbind(fluffy=c(1.1,1.2,1.3,1.4),misterCuddles=c(0.9,NA,1.1,1.0)) row.names(m) <- c("2013-01-01", "2013-01-02", "2013-01-03","2013-01-04") ``` Which gives me this: ``` fluffy misterCuddles 2013-01-01 1.1 0.9 2013-01-02 1.2 NA 2013-01-03 1.3 1.1 2013-01-04 1.4 1.0 ``` On every date, I'd like to know how many days in a row each cat has gone number 2. So the resulting matrix should look like this: ``` fluffy misterCuddles 2013-01-01 1 1 2013-01-02 2 0 2013-01-03 3 1 2013-01-04 4 2 ``` Is there a way to do this efficiently? The `cumsum` function does something similar, but that's a primitive so I can't modify it to suit my dirty, dirty needs. I could run a for loop and store a count like so: ``` m.output <- matrix(nrow=nrow(m),ncol=ncol(m)) for (column in 1:ncol(m)) { sum <- 0 for (row in 1:nrow(m)) { if (is.na(m[row,column])) sum <- 0 else sum <- sum + 1 m.output[row,column] <- sum } } ``` Is this the most efficient way to do this? I have a lot of cats, and I've recorded years worth of poop data. Can I parallellize this by column somehow?