R 数据操作月份级别
R data-manipulation month levels
我将 PA.csv 读入 R。
但是这里有一个问题:
为什么我的月级顺序是这样的?
levels(PA$Month)
[1] "1" "10" "11" "12" "2" "3" "4" "5" "6" "7" "8" "9"
如果我使用此数据通过 ggplot2 绘制图表,并且 x 轴为 PA$Month
,图形可以显示,但每个月的值顺序错误.
为了更简洁,情节的顺序显示 1, 10 , 11, 12, 2, 3,..., 9.
如何弄清楚这个?
$ Month : Factor w/ 12 levels "1","10","11",..: 1 5 6 7 8 9 10 11 12 2 ...
非常感谢。
exempleDf <- data.frame(month = as.character(c(10:12,1:9)), value= runif(12))
factor(exempleDf$month)
library(ggplot2)
# plot with level in wrong order
qplot(x = month, y = value, data = exempleDf)
# a simple way to reorder factor
exempleDf$month <- as.factor(as.numeric(exempleDf$month))
factor(exempleDf$month)
# plot with level in right order
qplot(x = month, y = value, data = exempleDf)
factor(exempleDf$month)
我将 PA.csv 读入 R。
但是这里有一个问题:
为什么我的月级顺序是这样的?
levels(PA$Month)
[1] "1" "10" "11" "12" "2" "3" "4" "5" "6" "7" "8" "9"
如果我使用此数据通过 ggplot2 绘制图表,并且 x 轴为 PA$Month
,图形可以显示,但每个月的值顺序错误.
为了更简洁,情节的顺序显示 1, 10 , 11, 12, 2, 3,..., 9.
如何弄清楚这个?
$ Month : Factor w/ 12 levels "1","10","11",..: 1 5 6 7 8 9 10 11 12 2 ...
非常感谢。
exempleDf <- data.frame(month = as.character(c(10:12,1:9)), value= runif(12))
factor(exempleDf$month)
library(ggplot2)
# plot with level in wrong order
qplot(x = month, y = value, data = exempleDf)
# a simple way to reorder factor
exempleDf$month <- as.factor(as.numeric(exempleDf$month))
factor(exempleDf$month)
# plot with level in right order
qplot(x = month, y = value, data = exempleDf)
factor(exempleDf$month)