[R] nested if/else very slow, more efficient ways?

Alex Brown alex at transitive.com
Tue Oct 24 00:23:33 CEST 2006


There are a number of ways this might be approached.

Can you please give a sample of your data, and your desired output?

Are "5a" ... "5e" the only values that appear in that column, or are  
there other values, "4e" for instance, that should stay the same  
during your conversion?

Do you wish to use the numbers 1 to 5 in the processed column in  
arithmetic processing, or are they just an enumeration of possible  
values?

While you think about it, I direct your attention to the functions:

sub
factor

-Alex

On 23 Oct 2006, at 23:03, Kim Milferstedt wrote:

> Hello,
>
> in the data.frame "resultsfuzzy" I would like to replace the
> characters in the second column ("5a", "5b", ... "5e") with numbers
> from 1 to 5. The data.frame has 39150 entries. I seems to work on
> samples that are << nrow(resultsfuzzy) but it takes suspicously long.
>
> Do you have any suggestions how to make the character replacing  
> more efficient?
>
> Code:
>
> for (i in 1:nrow(resultsfuzzy))
> {
> if (resultsfuzzy[i,2] == "5a"){resultsfuzzy[i,2] <- 1} else
>      if (resultsfuzzy[i,2] == "5b"){resultsfuzzy[i,2] <- 2} else
>          if (resultsfuzzy[i,2] == "5c"){resultsfuzzy[i,2] <- 3} else
>              if (resultsfuzzy[i,2] == "5d"){resultsfuzzy[i,2] <- 4}  
> else
>                  resultsfuzzy[i,2] <- 5
> }
>
> Thanks,
>
> Kim
>
> version
>
> platform i386-pc-mingw32
> arch     i386
> os       mingw32
> system   i386, mingw32
> status
> major    2
> minor    2.1
> year     2005
> month    12
> day      20
> svn rev  36812
> language R
>
> __________________________________________
>
> Kim Milferstedt
> University of Illinois at Urbana-Champaign
> Department of Civil and Environmental Engineering
> 4125 Newmark Civil Engineering Laboratory
> 205 North Mathews Avenue MC-250
> Urbana, IL 61801
> USA
> phone: (001) 217 333-9663
> fax: (001) 217 333-6968
> email: milferst at uiuc.edu
> http://cee.uiuc.edu/research/morgenroth
>
> ______________________________________________
> R-help at stat.math.ethz.ch 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.



More information about the R-help mailing list