我有以下data.frame,其中我想使用num列1:10将单词作为有序变量(正确的顺序为一,二,三等),这样如果我绘图(单词,num) ,单词应在x轴上按正确顺序排列。
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
我试过以下但不起作用:
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
我知道以下命令有效,但我想避免输入levels = c(“one”,“two”,“three”......):
ddf$words = ordered(ddf$words, levels=c("one","two","three","four","five","six","seven","eight","nine","ten"))
我需要以下情节:
感谢您的帮助。
答案 0 :(得分:2)
你可以试一试:
> w <- with(ddf, words[order(num)])
> ord <- ordered(ddf$words, levels = w)
> plot(ord, ddf$num, ylab = "NUMBER", xlab = "FACTOR")
答案 1 :(得分:1)
这是何时使用因子的完美示例,因为排序因子是基于级别的顺序
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
但是默认情况下情节会命令一个因子,所以您可以更改为一个字符,然后再将其更改为一个因子
ddf$words <- as.character(ddf$words)
ddf <- ddf2[order(ddf$num),]
ddf$words <- factor(ddf$words, levels=ddf$words)