SWR
SWR

Reputation: 507

Change to date format

I have some data with a date column:

enter image description here

The format here is month-year. However this column is in a factor format and I need it as a date.

> str(data$date)
 Factor w/ 211 levels "01-1994","01-1996",..: 88 157 125 137 139 106 11 204 45 173 ...

I tried to change it this way but the outcome was a column of NA's. Where is the error?

data$date <- as.Date(data$date, format = "%m-%Y")

enter image description here

Upvotes: 0

Views: 122

Answers (2)

A5C1D2H2I1M1N2O1R2T1
A5C1D2H2I1M1N2O1R2T1

Reputation: 193497

You may consider looking into the "zoo" package which has a yearmon format:

## Some sample data
test <- data.frame(date = c("05-2010", "09-2007", "01-2013"))
str(test)
# 'data.frame': 3 obs. of  1 variable:
#  $ date: Factor w/ 3 levels "01-2013","05-2010",..: 2 3 1

Converting to yearmon:

library(zoo)
as.yearmon(test$date, format="%m-%Y")
# [1] "May 2010" "Sep 2007" "Jan 2013"

FYI: It is possible to wrap as.yearmon in as.Date if you need the regular date format.

as.Date(as.yearmon(test$date, format="%m-%Y"))
# [1] "2010-05-01" "2007-09-01" "2013-01-01"

Upvotes: 3

Dirk is no longer here
Dirk is no longer here

Reputation: 368181

You do not have dates. You have a factor variable as str() tells you.

More generally, looks into stringsAsFactors=FALSE, either as an option to data reading (including from data base) or a global option.

For the issue at hand: combine

as.Date(paste0(as.character(date$date), "-01"), "%m-%Y-%d")

as you also need a day to create a valid date.

Upvotes: 1

Related Questions