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

Mike Nielsen mr.blacksheep at gmail.com
Tue Oct 24 00:21:58 CEST 2006


One way that might do what you want is to change the character column
to a factor, and then apply as.numeric.

resultsfuzzy$x<-as.numeric(factor(resultsfuzzy$x,levels=c("5a","5b","5c","5d","5e")))

This assumes, of course, that you know that the levels are going to be
in the set {5a,5b,5c,5d,5e}.

However, it may be better to just leave it as a factor, depending upon
what you intend to do with it later.

Hope this helps.

Regards,

Mike

On 10/23/06, Kim Milferstedt <milferst at uiuc.edu> 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.
>


-- 
Regards,

Mike Nielsen



More information about the R-help mailing list