Dear R-ers,
I have a list of data frames such that the length of the list is unknown in
advance (it could be 1 or 2 or more). Each element of the list contains a
data frame.
I need to loop through all rows of the list element 1 AND (if applicable)
of the list element 2 etc. and do something at each iteration.
I am trying to figure out how to write a code that is generic, i.e., loops
through the rows of all elements of my lists even if the total number of
the list elments is unknown in advance.
Below is an example.

a=expand.grid(1:2,1:2)
b=expand.grid(1:2,1:2,1:2)
#################################################
# My list that can have 1 element, e.g.:
l.short<-vector("list",1)
l.short[[1]]<-a
# I need to loop through rows of l.short[[1]] and do somethinig (it's
unimportant what exactly) with them, e.g.:
out<-vector("list",nrow(l.short[[1]]))
for(i in 1:nrow(l.short[[1]])){  # i<-1
  out[[i]]<-sum(l.short[[1]][i,])
}
(out)

#################################################
# Or my list could have >1 elements, e.g., 2 like below (or 3 or more).
# The total length of my list varies.

l.long<-list(a,b)
# I need to loop through rows of l.long[[1]] AND of l.long[[2]]
simultaneously
# and do something with both, - see example below.
# Below, I am doing it "manually" by using expand.grid to create all
combinations of rows of 2 elements of 'l.long':
mygrid<-expand.grid(1:nrow(l.long[[1]]),1:nrow(l.long[[2]]))
out<-vector("list",nrow(mygrid))
for(gridrow in 1:nrow(mygrid)){  # gridrow<-1
    row.a<-mygrid[gridrow,1]
    row.b<-mygrid[gridrow,2]
    out[[gridrow]]<-sum(l.long[[1]][row.a,])+sum(l.long[[2]][row.b,])
}
Thank you very much for any suggestions!
-- 
Dimitri Liakhovitski
gfk.com <http://marketfusionanalytics.com/>

        [[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.

Reply via email to