Skip to content

different way for a for loop for several columns?

1 message · ilai

#
Inline
On Tue, Feb 14, 2012 at 3:16 AM, Nerak T <nerak.t at hotmail.com> wrote:
?apply ?lapply ?tapply, etc. are just wrappers for building more
efficient loops. If you "think in loops" (which you shouldn't) you are
also thinking in "apply". The reason it may seem like an endless maze
is because you use different wrappers for looping over different
object classes and indices, but at the end, the call to apply() is
similar to calling for().
e.g. consider a matrix with dimensions n x p. To sum rows you could
for(i in 1:n) sum(matrix[i,])
But better apply(matrix, 1 , sum)  # where the 1 denotes the 1st
dimension (rows)
Same thing for  sum columns
for(j in 1:p) sum(matrix[,j])
But better apply(matrix, 2 , sum)  # where the 2 denotes the 2nd
dimension (columns)

The same "stuff" that goes in the loop can go to apply with small
syntax changes. e.g.

ll<- list(1:5,1:10,letters)
out<- list()
for(L in 1:3){
# ...
# ... a bunch of complicated functions/calculations
# ...
out[[ L ]] <- length( ll[[ L ]] )
}
out

Can be replaced with

lapply( ll, function(L) {
# ...
# ... a bunch of complicated function/calculations
# ...
length(L)
} )

This time use lapply since you are looping over L elements of the list ll.
???

xx<- c(0,10,100)   # declare xx
print(xx)
rnorm(3,xx)          # use it
rm(xx)                 # remove xx
rnorm(3, xx<- c(0,10,100))   define and use it "at the same time"
print(xx)
Only in loops. What happens is you need to create a "storage" for the
result of your loop, since the objects created in the loop are
overwritten at each step:
for(i in 1:10) cat( i, '\n' )
i     # i =  10 everything before was overwritten
See my lapply example for creating "empty" storage.
You don't put it anywhere, it was in answer to your comment: " but
it?s not that I have created a function that has to be applied on a
whole column, calculations are done for the different rows?"

So, no! calculations are done on the object (which has some dimension
or is a list), only in rare cases do you need to loop over each
element (or dimension) of the object itself.
Pleasure. Good luck !