Skip to content

How can I avoid nested 'for' loops or quicken the process?

3 messages · Brigid Mooney, Charles C. Berry, David Winsemius

#
On Mon, 22 Dec 2008, Brigid Mooney wrote:

            
Unfortunately, you have given nothing that is reproducible.

The details of MyFunction and the exact structure of the list objects are 
crucial.

Check out the _Posting Guide_ for hints on how to formulate a question 
that will elecit an answer that helps you.

HTH,

Chuck
Charles C. Berry                            (858) 534-2098
                                             Dept of Family/Preventive Medicine
E mailto:cberry at tajo.ucsd.edu	            UC San Diego
http://famprevmed.ucsd.edu/faculty/cberry/  La Jolla, San Diego 92093-0901
#
I do agree with Dr Berry that your question failed on several grounds  
in adherence to the Posting Guide, so this is off list.

Maybe this will give you  guidance that you can apply to your next  
question to the list:

 > alist <- list("a","b","c")
 > blist <- list("ab","ac","ad")

 > expand.grid(alist, blist)
   Var1 Var2
1    a   ab
2    b   ab
3    c   ab
4    a   ac
5    b   ac
6    c   ac
7    a   ad
8    b   ad
9    c   ad

 > apply( expand.grid(alist, blist), 1, function(x) paste(x[1], x[2],  
sep=""))
[1] "aab" "bab" "cab" "aac" "bac" "cac" "aad" "bad" "cad"

 > clist <- list("AA","BB")

 > apply(expand.grid(alist, blist, clist),1,function(x) paste(x[1],  
x[2], x[3], sep=""))
  [1] "aabAA" "babAA" "cabAA" "aacAA" "bacAA" "cacAA" "aadAA" "badAA"  
"cadAA" "aabBB"
[11] "babBB" "cabBB" "aacBB" "bacBB" "cacBB" "aadBB" "badBB" "cadBB"

 > dlist <- list(TRUE,FALSE)

 > apply(expand.grid(alist, blist, clist, dlist),1,function(x)  
paste(x[1], x[2], x[3], (x[4]), sep=""))[8:12]
[1] "badAATRUE" "cadAATRUE" "aabBBTRUE" "babBBTRUE" "cabBBTRUE"


This could get unwieldily if the length of the lists are appreciable,  
since the number of rows will be the product of all the lengths. On  
the other hand you could create a dataframe indexed by the variables  
in expand.grid's output:

 >  master.df <- data.frame( expand.grid(alist, blist, clist, dlist),
                             results = apply(expand.grid(alist, blist,  
clist,dlist),1,
                                     function(x) paste(x[1], x[2],  
x[3], (x[4]), sep="")))