[R] repeating values in levels()

Peter Ehlers ehlers at ucalgary.ca
Sun Oct 18 00:36:56 CEST 2009


Donald Braman wrote:
> Can someone help me understand this results?
> 
>> levels(as.factor(miset1$facts_convict))
> [1] "1" "1" "2" "3" "4" "5" "6"

Don't know how you got your data that way, but I
wonder if you've done str() on your data after
whatever procedure you used to get to this stage.

Here's one way to get this pathological state:

  set.seed(2)
  x <- sample(5, 15, rep=TRUE)
  y <- factor(x, levels=c(1, 1:5))  ## repeating level "1"
  levels(y)
  [1] "1" "1" "2" "3" "4" "5"

> 
> converting to numeric and back doesn't seem to help:
> 
>> levels(as.factor(as.numeric(miset1$facts_convict)))
> [1] "1" "1" "2" "3" "4" "5" "6"

I suspect that miset1$facts_convict is already a factor
[str() would tell you] and that the following comment
from ?factor applies:

"In particular, as.numeric applied to a factor is meaningless ..."

If my guess is correct, you should be able to fix things with

  newy <- factor(y)
  levels(newy)
  [1] "1" "2" "3" "4" "5"


  -Peter Ehlers

> 
> It's messing up my ologits.  Any way to correct this?
> 


> ______________________________________________
> 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.
> 
>




More information about the R-help mailing list