转换日期并订购数据框?

时间:2014-03-08 00:20:13

标签: r date

我在下面添加了我的数据。我想将ind column'class转换为date(这是现在的一个因素)。此外,我想根据月份订购我的数据框架,该月份将从1月开始到12月结束。有人可以帮我吗?

structure(list(values = c(36L, 36L, 23L, 38L, 249L, 31L, 20L, 
28L, 36L, 35L, 41L, 43L), ind = structure(1:12, .Label = c("April", 
"August", "December", "February", "January", "July", "June", 
"March", "May", "November", "October", "September"), class = "factor")), .Names = c("values", 
"ind"), row.names = c(NA, -12L), class = "data.frame")

2 个答案:

答案 0 :(得分:1)

foo$ind <- as.Date(paste("2014", "1", foo$ind), format = "%Y %d %b")
foo[order(foo$ind),]
##    values        ind
## 5     249 2014-01-01
## 4      38 2014-02-01
## 8      28 2014-03-01
## 1      36 2014-04-01
## 9      36 2014-05-01
## 7      20 2014-06-01
## 6      31 2014-07-01
## 2      36 2014-08-01
## 12     43 2014-09-01
## 11     41 2014-10-01
## 10     35 2014-11-01
## 3      23 2014-12-01

答案 1 :(得分:1)

假设您实际上并不想要日期(因为日期包括年,日和月,而您只有几个月):

foo$ind <- factor(foo$ind, levels = month.name)
foo <- foo[order(foo$ind), ]
foo
   values       ind
5     249   January
4      38  February
8      28     March
1      36     April
9      36       May
7      20      June
6      31      July
2      36    August
12     43 September
11     41   October
10     35  November
3      23  December