# [R] apply is making me crazy...

Dennis Murphy djmuser at gmail.com
Thu Jul 28 04:30:30 CEST 2011

```Hi:

Try this:

exampGood = lapply(2:4, function(x) matrix(rnorm(10 * x), ncol = x))
exampBad  = lapply(1:3, function(x) matrix(rnorm(10 * x), ncol = x))

csfun <- function(m) {
if(ncol(m) == 1L) {return(m)} else {
t(as.matrix(apply(m, 1, cumsum)))
}
}

lapply(exampGood, csfun)

HTH,
Dennis

On Wed, Jul 27, 2011 at 3:22 PM, Gene Leynes <gleynes+r at gmail.com> wrote:
> I have tried a lot of ways around this, but I can't find a way to make apply
> work in a generalized way because it causes a failure whenever reduces the
> dimensions of its output.
> The following example is easier to understand than the question.
>
> I wish it had a "drop=TRUE/FALSE" option like the "["  (and I wish I had
> found the drop option a year ago, and I wish that I had 1e6 dollars... Oops,
> I mean euros).
>
>
>    ## Make three example matricies
>    exampGood = lapply(2:4, function(x)matrix(rnorm(1000*x),ncol=x))
>    ## Two ways to see what was created:
>    for(k in 1:length(exampGood)) print(dim(exampGood[[k]]))
>
>    ##  Take the cumsum of each row of each matrix
>    answerGood = lapply(exampGood, function(x) apply(x ,1,cumsum))
>
>    ##  Take the first element of the final column of each answer
>        LastColumn = ncol(mat)
>        print(mat[1,LastColumn])
>    }
>        LastColumn = ncol(mat)
>        print(mat[1,LastColumn])
>    }
>
>        [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help