user233531
user233531

Reputation: 331

converting a factor column into a date within a dataset in R

I have a dataset which contains a date like this 2.01.2006 00:00 but when I read the file it was converted into a factor. I want to convert it into Date type. I have used these two methods for the conversion but I am getting NAs instead:

1) mydata$date = as.Date(mydata$date, format = "%m/%d/%Y %H:%M")

2) mydata$date <- strptime(x = as.character(mydata$date), format = "%d/%m/%Y %H:%M")

What is the mistake in these two lines?

Upvotes: 0

Views: 33

Answers (2)

akrun
akrun

Reputation: 886968

We can also use anydate from anytime

library(anytime)
mydata$date <- anydate(mydata$date)

Using a reproducible example

str1 <- "2.01.2006 00:00"
anydate(str1)
#[1] "2006-02-01"

Upvotes: 1

Tim Biegeleisen
Tim Biegeleisen

Reputation: 520948

Well your date uses period as a separator, so your format mask should match this:

mydata$date <- as.Date(mydata$date, format = "%m.%d.%Y %H:%M")

For the sample data you gave:

2.01.2006 00:00

the following date is output:

[1] "2006-02-01"

Upvotes: 1

Related Questions