24

I've the following data from a data frame

Name,JoiningDate,AmtPaid
Joe,12/31/09,1000
Amy,10/28/09,100
John,05/06/10,200

The Joining Date is coming in as a factor (when I sapply). How can I convert this to date and then sort on JoiningDate?

isomorphismes
  • 8,233
  • 9
  • 59
  • 70
Jayanth
  • 587
  • 1
  • 4
  • 15

3 Answers3

51

This should do it (where df is your dataframe)

df$JoiningDate <- as.Date(df$JoiningDate , format = "%m/%d/%y")

df[order(df$JoiningDate ),]
Aren Cambre
  • 6,540
  • 9
  • 30
  • 36
Tom Liptrot
  • 2,273
  • 21
  • 23
  • I'm having a similar problem. How it is possible that `mode(as.Date(df$JoiningDate, "%m/%d/%Y"))` returns `numeric` ? – isomorphismes Sep 05 '11 at 23:37
  • 3
    @ Lao Tzu you should open up a new question, your query may not get seen here. I believe that internally, dates are stored as numeric seconds since the start of Unix time (1st January 1970). Hope this helps. – richiemorrisroe Sep 06 '11 at 11:18
  • 5
    When I do this, it's turning my column into NAs – Travis Heeter Oct 07 '16 at 18:35
  • 1
    @TravisHeeter try this package, most likely your date is in a different format than what `as.Date` understands https://cran.r-project.org/web/packages/anytime/anytime.pdf – Vlady Veselinov Feb 27 '18 at 23:34
  • I get same issue as @TravisHeeter, date column become `NA`s. – ah bon Apr 10 '20 at 03:11
5

try this package, works wonders, and was made for date/time...

library(lubridate)
Portfolio$Date2 <- mdy(Portfolio.all$Date2)
Ray Kodiak
  • 69
  • 1
  • 13
0

The data.table package has its IDate class and functionalities similar to lubridate or the zoo package. You could do:

dt = data.table(
  Name = c('Joe', 'Amy', 'John'),
  JoiningDate = c('12/31/09', '10/28/09', '05/06/10'),
  AmtPaid = c(1000, 100, 200)
)

require(data.table)
dt[ , JoiningDate := as.IDate(JoiningDate, '%m/%d/%y') ]
andschar
  • 3,504
  • 2
  • 27
  • 35