On Jul 27, 2011, at 6:22 PM, Gene Leynes 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))
Try instead:
answerBad = lapply(exampBad, function(x) as.matrix(apply(x ,
1:1,cumsum)))
I also find wrapping as.matrix() around vector results inside a
print() call often makes my console output much more to my liking.
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@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.
David Winsemius, MD
West Hartford, CT
______________________________________________
R-help@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.