无法按日期对数据进行排序

时间:2013-09-23 09:50:06

标签: r dataframe

我有一个包含股票名称,价格和交易日的数据框。像这样:

        x     tradedate trading_volume trading_value 
     1 JIG    03/01/2012     055556               23
     2 JIG    04/01/2012     111111               43
     3 ABC    03/01/2012     715455               73
     4 ABC    04/01/2012     000000               39

我想按日期对数据进行排序。我试过这段代码:

df$tradedate = as.Date(df$tradedate, format="%d.%m.%Y")
df[with(df, order(df$tradedate)), ]

还有这个:

df[order(as.Date(df$tradedate, format="%d/%m/%Y")),]

但它不起作用:代码运行......但数据没有订购!

1 个答案:

答案 0 :(得分:2)

my.data <- read.table(text='
        x     tradedate trading_volume trading_value 
      JIG    03/01/2012     055556               23
      JIG    04/01/2012     111111               43
      ABC    03/01/2012     715455               73
      ABC    04/01/2012     000000               39
', header=TRUE)
my.data

my.data$tradedate <- as.Date(my.data$tradedate, format = "%d/%m/%Y")
my.data

my.data2 <- my.data[order(my.data$tradedate),]
my.data2

    x  tradedate trading_volume trading_value
1 JIG 2012-01-03          55556            23
3 ABC 2012-01-03         715455            73
2 JIG 2012-01-04         111111            43
4 ABC 2012-01-04              0            39