[R] a for loop to lapply
Kenn Konstabel
lebatsnok at gmail.com
Wed Mar 30 09:43:17 CEST 2011
Hi Alex,
lapply is not a substitute for for, so it not only does things
differenly, it does a different thing.
> Shadowlist<-array(data=NA,dim=c(dimx,dimy,dimmaps))
> for (i in c(1:dimx)){
> Shadowlist[,,i]<-i
> }
Note that your test case is not reproducible as you haven't defined
dimx, dimy, dimmaps.
> returni <-function(i,ShadowMatrix) {ShadowMatrix<-i}
> lapply(seq(1:dimx),Shadowlist[,,seq(1:dimx)],returni)
> So far I do not get same results with both ways.
> Could you please help me understand what might be wrong?
I don't suppose you're getting any results with lapply this way at all.
1. The second argument to lapply should be a function but here you
have something else.
2. Lapply returns a list of results and does *not* modify its
arguments. If you really want to, you can use <<- within lapply, so
your example (slightly modified) could look something like this:
A<-B<- array(data=NA,dim=c(5,5,5))
for (i in c(1:5))A[,,i]<-i
lapply(1:5, function(i) B[,,i][]<<-i)
all.equal(A,B)
Notice that in this case, what lapply returns is not identical to what
it does to B, and this is not nice. The normal use of lapply is
applying a function to each element of a list (or a vector)...
C<- lapply(1:5, diag) # a list with 5 elements, matrices with increasing size
lapply(C, dim) # dimensions of each matrix
# sapply would give it in a more convenient form
# or you could print it more concisely as str(lapply(C, dim))
the equivalent with for would be:
for(i in 1:5) print(dim(C[[i]]))
The _for_ version is less short and there are much more ['s and ('s to
take care about so lapply/sapply is easier here. Notice also that it
creates a new variable (i) or potentially overwrites anything named i
in your workspace. Lapply doesn't do it unless you explicitly tell it
to (using things like <<- , not recommended).
Good luck,
Kenn
More information about the R-help
mailing list