2012-09-25 18 views
0

我正在嘗試使用年份和月份信息對矢量進行排序。我從Date類型變量中獲得年份和月份。這裏是什麼,我試圖完成一個例子:如何在R中使用年份和月份進行排序(使用動物園包中的as.yearmon)

example <- as.Date(c("2010-04-22", "2010-04-26", "2010-04-26", 
    "2010-06-04", "2010-06-07", "2010-06-18", "2010-06-21", 
    "2010-07-14", "2010-07-16", "2010-07-30", "2010-08-20")) 

mes_ano <- as.character(as.yearmon(as.Date(example))) 

mes_ano <- factor(mes_ano, levels = c(unique(mes_ano), 
"mai 2010", "set 2010", "out 2010", "nov 2010")) 

現在我想按年份和月份進行排序mes_ano,但我不知道怎麼辦。

其實,我真正的目標是對水平進行排序,因爲我會用ggplot2繪製一個圖表,並且我需要對這些圖層進行排序。但我認爲,如果我只是詢問關於整理載體的信息,它會讓我們的生活更輕鬆。然後我可以弄清楚如何對關卡進行排序。

+0

爲什麼不只是排序'示例'而不是? –

+0

因爲當我將mes_ano更改爲factor時,mes_ano未按正確的方式排序。我可以手動設置每個因素的級別順序,但在我的實際數據集中,級別數量太大,所以它會非常麻煩。 –

+0

剛剛如何:'plot(as.yearmon(example),rnorm(11))' –

回答

1

我想你想使用葡萄牙語的月份名稱。讓我們去:

您的數據:

example <- as.Date(c("2010-04-22", "2010-04-26", "2010-04-26", 
        "2010-06-04", "2010-06-07", "2010-06-18", "2010-06-21", 
        "2010-07-14", "2010-07-16", "2010-07-30", "2010-08-20")) 

我們需要用這些名字一個向量:

port_mon <- c("jan", "fev", "mar", "abr", "mai", "jun", 
       "jul", "ago", "set", "out", "nov", "dez") 

現在,對數據進行排序:

ex_sorted <- sort(example) 

選擇正確的月份名稱葡萄牙語:

month_names <- port_mon[as.numeric(format(ex_sorted, "%m"))] 

結合月份和年份:

mes_ano <- paste(month_names, format(ex_sorted, "%Y")) 

創建因素:

mes_ano_fac <- factor(as.yearmon(ex_sorted), labels = unique(mes_ano)) 

圖(一個用於演示目的在y軸無意義的數據):

library(ggplot) 

qplot(x = mes_ano_fac, y = seq(length(example))) 

enter image description here

+0

謝謝。我會嘗試一下,如果它起作用(就像它似乎那樣),我會選擇它作爲我接受的答案。再次感謝。 –