[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)
lapply(exampBad, 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))
>    exampBad  = lapply(1:3, 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]]))
>    for(k in 1:length(exampBad)) print(dim(exampBad[[k]]))
>
>    ##  Take the cumsum of each row of each matrix
>    answerGood = lapply(exampGood, function(x) apply(x ,1,cumsum))
>    answerBad  = lapply(exampBad, function(x) apply(x ,1,cumsum))
>    str(answerGood)
>    str(answerBad)
>
>    ##  Take the first element of the final column of each answer
>    for(mat in answerGood){
>        LastColumn = ncol(mat)
>        print(mat[1,LastColumn])
>    }
>    for(mat in answerBad){
>        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
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>



More information about the R-help mailing list