0

When I read in a data file using R, a Date variable is a Factor.

For example, let epc hold the data set. Then if we look at the structure of the first date, we get

str(epc$Date[1]) Factor w/ 1 level "16/12/2006": 1

If you were to convert this to a character, as.character(epc$Date[1]), you'd get exactly the same thing: "16/12/2006"

No matter what I've tried, I can't convert this type of object into a valid date.

if the date is "16/12/2006" (which I'm assuming is Dec. 16th, 2006), then as.Date(epc_full$Date[1]) gives "0016-12-20" -- the full year is lost.

I've tried many different things, e.g., first converting the date into a character, trying different versions of as.Date(), etc., but I keep getting exactly the same result when the input is "16/12/2006"

What's the trick here?

Christopher Skyi
  • 229
  • 1
  • 3
  • 12

2 Answers2

0

So first, for some reason this is being read in as a factor with a level that is labeled "16/12/2006". You are converting this to a character, so I'll start there.

There are a number of ways to do this, but I think the easiest is to use the lubridate package.

#Install package
install.packages("lubridate")
library(lubridate)

yourTextDate <- "16/12/2006"

yourDate <- dmy(yourTextDate)

yourDate
user3055034
  • 593
  • 1
  • 5
  • 14
0

If you strictly want a Date class, then:

as.Date(s, format='%d/%m/%Y')
## [1] "2006-12-16"
class(.Last.value)
## [1] "Date"

So you can convert the entire column of dates with:

as.Date(epc$Date, format='%d/%m/%Y')

This should work whether it is a character or factor.

lubridate works well as well, but if you're sticking with base R, this works well too.

r2evans
  • 141,215
  • 6
  • 77
  • 149