[R] a for loop to lapply
Dieter Menne
dieter.menne at menne-biomed.de
Wed Mar 30 10:03:26 CEST 2011
alaios wrote:
>
> I am trying to learn lapply.
> I would like, as a test case, to try the lapply alternative for the
> Shadowlist<-array(data=NA,dim=c(dimx,dimy,dimmaps))
> for (i in c(1:dimx)){
> Shadowlist[,,i]<-i
> }
> ---so I wrote the following---
> returni <-function(i,ShadowMatrix) {ShadowMatrix<-i}
> lapply(seq(1:dimx),Shadowlist[,,seq(1:dimx)],returni)
>
>
The basic problem is that you have an array, but you name it "list". This is
valid code, but by calling it so you shot a list-bullet into your
vector-foot. An array should be treated like an array, and the best way to
fill it uses simple vectoring. No loop, no xapply needed.
Use lapply if you have a data.frame or (more generic) a real list, which can
contain rather heterogeneous components. And try to forget what you learned
in your c++ course: Seeing
lapply(,Shadowlist[,,seq(1:dimx)],)
to fill Shadowlist tell me that it must be wrong, because R (in all
recommended cases) never "fills" a parameter passed to it like c(++) can do.
You should always have something like:
Shadowlist <- lapply(....)
Dieter
#------
dimx=2 # don't forget to make the example self-contained
dimy=3
dimmaps=3
ShadowArray<-array(data=NA,dim=c(dimx,dimy,dimmaps))
# Are you shure you mean "dimx" ? But let's assume it is correct
for (i in c(1:dimx)){
ShadowArray[,,i]<-i
}
ShadowArray
ShadowArray<-array(data=NA,dim=c(dimx,dimy,dimmaps))
ShadowArray[,,1:dimx]<-1:dimx
ShadowArray
--
View this message in context: http://r.789695.n4.nabble.com/a-for-loop-to-lapply-tp3417169p3417377.html
Sent from the R help mailing list archive at Nabble.com.
More information about the R-help
mailing list