ycc1017
ycc1017

Reputation: 3

Change text to date formate in R

I am trying to extract the date from a column of text in formate of "mm/dd/yyyy".

> head(X$A1)
[1]            
2456 Levels:   1/1/2007 1/1/2008 1/1/2009 1/1/2012 1/10/2005 1/10/2006 1/10/2007 ... 9/9/2016

I then use as.date to extract the year in the date with decimal places. However, it returns with NA...

> X$dates <- as.Date(X$A1, "%m/%d/%Y")

> head(X$dates)
[1] NA NA NA NA NA NA

How can I get the date express in the number of year with decimals? Thanks!

Upvotes: 0

Views: 92

Answers (2)

Maurits Evers
Maurits Evers

Reputation: 50678

I assume you are asking how to convert a date to a decimal of its year.

We can use lubridate::decimal_date for that

# Sample data
date <- c("1/1/2007 1/1/2008 1/1/2009 1/1/2012 1/10/2005 1/10/2006 1/10/2007")
date <- unlist(strsplit(date, " "))
date
#[1] "1/1/2007"  "1/1/2008"  "1/1/2009"  "1/1/2012"  "1/10/2005" "1/10/2006"
#[7] "1/10/2007"

# Convert to decimal dates
lubridate::decimal_date(as.Date(date, format = "%m/%d/%Y"))
#[1] 2007.000 2008.000 2009.000 2012.000 2005.025 2006.025 2007.025

Upvotes: 0

HolgerBarlt
HolgerBarlt

Reputation: 317

Have you tried:

X$dates <- as.Date(as.character(X$A1), "%m/%d/%Y")

Upvotes: 1

Related Questions