user2794659
user2794659

Reputation: 145

Cannot sort data frame by date

I have a data frame with stocks names, prices and trading days. Like this:

        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

I want to sort the data by date. I tried this code:

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

and also this:

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

But it doesn't work: There code runs... but the data is not ordered!

Upvotes: 2

Views: 235

Answers (1)

Mark Miller
Mark Miller

Reputation: 13123

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

Upvotes: 2

Related Questions