[R] factor level for non-existing value

Petr PIKAL petr.pikal at precheza.cz
Thu Feb 9 13:38:49 CET 2012


Hi

> 
> Hello everybody!
> 
> Let's assume I have the following factor with it's levels:
> 
> a<-factor(c(2,3,3,2,4,2,3,2,2,2,3,2,3))
> mydata<-data.frame(a)
> 
> When I plot the vector "a" using
> 
> barplot(table(mydata$a)
> 
> unfortunately the value "1" does not
> show up, as it does not appear in my data.
> But still, it theoretically exists.
> 
> How can I assign the following levels to the factor?
> 
> 1: dislike very much
> 2: dislike
> 3: like
> 4: like very much
> 
> I have already tried the following code, which does not work
> levels(data$a)<-c("dislike very much","dislike","like","like very much")
> as "2" then becomes "dislike very much".

you can do it when constructing a factor

a<-factor(c(2,3,3,2,4,2,3,2,2,2,3,2,3), levels=1:4,labels=c("dislike very 
much","dislike","like","like very much"))

or when you already have a factor

a<-factor(a, levels=1:4)

I basically understand that factor is a vector of numeric values with 
levels and labels attribute. Each level can have some label which can be 
changed independently. All levels does not need to be present in a factor.

However you shall not confuse it with function ?labels which has nothing 
to do with factors.

Regards
Petr




> 
> I hope you understand my problem.
> 
> Thank you for any help!
> 
>    [[alternative HTML version deleted]]
> 
> ______________________________________________
> 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