0

I used to have my ordinal data as plain numbers in the data frame (i.e. 1-3). This worked out fine, but I had to remember what the numbers stood for (in my case: 1=Low, 2=Medium, 3=High).

To make things easier to me I am trying to get R to display names/labels instead of 1-3 in a generic fashion, i.e. regardless of whether I am using tables, boxplots, etc. However, I can't get this to work.

I tried

data$var <- ordered(data$var, 
    levels = c(1, 2, 3), 
    labels = c("Low", "Medium", "High")) 

After I do this, a

boxplot(data$var)

does not work anymore. Why not?

Phil
  • 175
  • 1
  • 9
  • 3
    You might want to include some toy code so your error can be reproduced. Best way to do that is `dput` an extract of your data frame (anonymised if need be). – Akhil Nair Aug 05 '15 at 12:22
  • 1
    [How to make a great R reproducible example?](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) – zx8754 Aug 05 '15 at 12:24

2 Answers2

2

The command didn't work because boxplot is expecting the first argument (the x argument), to be numeric.

If you're only looking for a simple solution, you could simply plot the data as integers (as your factors are ordered, therefore they will be in the right integer order) suppress the original axes and add a new one with the right axis labels.

boxplot(as.integer(data$var), yaxt = "n")
axis(2, at = c(1, 2, 3), labels = c("Low", "Medium", "High"))
Akhil Nair
  • 3,144
  • 1
  • 17
  • 32
  • So there is no way to get boxplot to accept ordinal-scale variables? That sucks. Anyway, thanks, your code works fine; however it removes both axes' labels. Can I just replace ONE axis or is there a simple command to re-add the x-axis labels? – Phil Aug 05 '15 at 14:34
0

Assuming the independent variable you want to plot is already a factor, here is a general way to re-order the levels and labels:

# Let's say you have a factor in the default alphabetical order

my.fac <- factor(LETTERS[1:3])
str(my.fac)

# Now you want to reorder it arbitrarily:

levels(my.fac) <- list(A = "A", C = "C", B = "B")
str(my.fac) # they have been reordered

# You can also use this method to rename the levels,
# with or w/o changing the order:

levels(my.fac) <- list("Low" = "A", "Med" = "B", "High" = "C")
str(my.fac)

# The general format is list("new" = "old")

If your original data is not a factor, then you can begin by coercing with as.factor.

Bryan Hanson
  • 6,055
  • 4
  • 41
  • 78