Skip to content
Prev 325442 / 398503 Next

How can make loop more faster?

On Jun 15, 2013, at 2:38 PM, Fabrice Tourre wrote:

            
Did you attach a file with a non-'.txt' extension?
I'm guessing that using `ifelse` would be much faster than going column by column and and then row by painful row through this testing with nested `if(cond){conseq}else{alter}` . You should gain efficiency by setting up the results of the `strsplit` operation on a full column at a time. Build a function that would work one column at a time and then lapply it to the dataframe.
You could leave the "==max.allelle" test on the outer of nested ifelse operations to "overwrite" the resutls of the testing of the two split-bits. But I would make it a %in%-test so that it won't fail when mor than one maximum occur.

Perhaps (untested and a lot of guesswork):

testsplitfunc <- function(col){
         temptbl <- table(col)
         tempspl <-  strsplit(as.character(col) , split=" ")
         allele <-cbind( sapply(temp, "[", 1),
                         sapply(temp, "[", 2) )
         res <- ifelse ( col %in% names(temptbl)[ which(tbl==max(temptbl))] , 
                     0,
                     ifelse( allele[,1]==allele[,2], 2, 1) )
         is.na(res) <- col=="0 0"
         }

code.top20 <- do.call(cbind, lapply(top20.dat, testsplitfunc) )
In the absence of a problem description I will leave the details unaddressed.
David Winsemius
Alameda, CA, USA