0

I am new to R. I've made a boxplot of my data but currently R is sorting the factors alphabetically. How do I maintain the original order of my data? This is my code:

boxplot(MS~Code,data=Input)

I have 40 variables that I wish to boxplot in the same order as the original data frame lists them. I've read that I may be able to set sort.names=FALSE to maintain the original order by I don't understand where that piece of code would go.

Is there a way to redefine my Input before it goes into boxplot?

Thank you.

val
  • 1,629
  • 1
  • 30
  • 56

1 Answers1

1

factor the variable again as you wish in line 3

data(InsectSprays)
data <- InsectSprays
data$spray <- factor(data$spray, c("B", "C", "D", "E", "F", "G", "A"))
boxplot(count ~ spray, data = data, col = "lightgray")

The answer above is 98% of the way there.

set.seed(1)
# original order is E - A
Input <- data.frame(Code=rep(rev(LETTERS[1:5]),each=5),
                    MS=rnorm(25,sample(1:5,5)))
boxplot(MS~Code,data=Input)   # plots alphabetically

Input$Code <- with(Input,factor(Code,levels=unique(Code)))
boxplot(MS~Code,data=Input)   # plots in original order

jlhoward
  • 58,004
  • 7
  • 97
  • 140
Zhilong Jia
  • 2,329
  • 1
  • 22
  • 34
  • There must be an easier way? I have 40 factors and I don't want to be trying to figure out which comes first. They are already in order when I bring them into R. – val Dec 01 '14 at 23:39
  • 1
    Use `data$spray <- with(data,factor(spray,levels=unique(spray)))` – jlhoward Dec 02 '14 at 00:01