[R] Simple loop code

David Winsemius dwinsemius at comcast.net
Thu Apr 29 17:05:27 CEST 2010


On Apr 29, 2010, at 10:37 AM, RCulloch wrote:

>
> Thanks Henrique,
>
> that works! for anyone else as slow as me, just:
>
> ##Assign
> x <- factor(dat.ID$ID2, labels = 1:7)
> ##Convert to dataframe
> x <- as.data.frame(x)

The more typical methods for converting a factor to a character vector  
would be:

(ff <- factor(substring("statistics", 1:10, 1:10), levels=letters))
  levels(ff)[ff]
# [1] "s" "t" "a" "t" "i" "s" "t" "i" "c" "s"
  as.character(ff)
# [1] "s" "t" "a" "t" "i" "s" "t" "i" "c" "s"

> ##Then bind to your data
> z <- cbind(y,x)

Oooh. Not a good practice, at least for the newish useR. cbind and  
rbind create matrices and as a consequence coerce all of their  
elements to be of the same type. Numeric columns would become  
character vectors. Not generally a desired result. This would be safer:

dat.I$ID2.cf  <- as.character( factor(dat.ID$ID2, labels = 1:7)  )
-- 
David.
>
> Thanks again, I expected it to be more complicated!
>
> Cheers,
>
> Ross
> -- 
> View this message in context: http://r.789695.n4.nabble.com/Simple-loop-code-tp2075322p2075586.html
> Sent from the R help mailing list archive at Nabble.com.
>
> ______________________________________________
> R-help at 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.

David Winsemius, MD
West Hartford, CT



More information about the R-help mailing list