rnso
rnso

Reputation: 24535

ordering one column using order in second in R

I have following data.frame in which I want to make words as an ordered variable (in correct order of one, two, three etc) using num column 1:10, so that if I do plot(words, num), words should come in correct order on x axis.

ddf = structure(list(num = c(3L, 4L, 5L, 1L, 2L, 8L, 10L, 9L, 6L, 7L
), words = structure(c(9L, 3L, 2L, 5L, 10L, 1L, 8L, 4L, 7L, 6L
), .Label = c("eight", "five", "four", "nine", "one", "seven", 
"six", "ten", "three", "two"), class = "factor")), .Names = c("num", 
"words"), class = "data.frame", row.names = c(NA, -10L))

ddf
num words
3 three
4 four
5 five
1 one
2 two
8 eight
10 ten
9 nine
6 six
7 seven

I tried following but it does not work:

ddf$words = ordered(ddf[order(ddf$num),]$words)
 [1] one   two   three four  five  six   seven eight nine  ten  
Levels: eight < five < four < nine < one < seven < six < ten < three < two

I know following command works but I want to avoid entering levels=c("one","two","three"....):

ddf$words = ordered(ddf$words, levels=c("one","two","three","four","five","six","seven","eight","nine","ten"))

I need following plot: enter image description here

Thanks for your help.

Upvotes: 0

Views: 74

Answers (2)

Rich Scriven
Rich Scriven

Reputation: 99331

You could give this a shot:

> w <- with(ddf, words[order(num)])
> ord <- ordered(ddf$words, levels = w)
> plot(ord, ddf$num, ylab = "NUMBER", xlab = "FACTOR")

enter image description here

Upvotes: 2

JeremyS
JeremyS

Reputation: 3525

This is the perfect example of when to use factors, because ordering a factor is based on the order of the levels

ddf$words <- factor(ddf$words, levels=c("one","two","three","four","five","six","seven","eight","nine","ten"))

ddf[order(ddf$num),2] # has the same effect without setting the levels of a factor

But plot orders a factor by default, so you can change to a character, order it then change back to a factor

ddf$words <- as.character(ddf$words)
ddf <- ddf2[order(ddf$num),]
ddf$words <- factor(ddf$words, levels=ddf$words)

Upvotes: 1

Related Questions