[R] factor level for non-existing value

Ista Zahn istazahn at gmail.com
Thu Feb 9 13:49:33 CET 2012


Hi David,

On Thursday, February 09, 2012 01:21:48 PM David Studer wrote:
> 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)

#You need to specify levels and labels here, like this:

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"))

Then barplot will plot all four factor levels.

barplot(table(a))

This is pretty basic stuff, likely to be covered in most introductory texts, 
so I suggest you take some time to read an introduction to R.

Best,
Ista

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