ILA
ILA

Reputation: 3

Trouble reformatting date with as.Date

I'm having a simple problem and I can't tell what's wrong. I'm trying to convert dates formatted "YYYY-MM-DD" to "m/d/YYYY". On my machine, this code:

x <- as.Date("2000-01-01")
x <- as.Date(x, format = "%m/%d/%Y")
print(x)

returns

"2000-01-01"

What am I missing?

Upvotes: 0

Views: 37

Answers (1)

joran
joran

Reputation: 173567

as.Date() creates a date object where you tell it how to interpret the input with a format argument.

format() (or alternatively strftime()) will convert a date object to a character object in a desired format:

x <- as.Date("2000-01-01")
x
[1] "2000-01-01"

str(x)
Date[1:1], format: "2000-01-01"

y <- format(x = x,format = "%m/%d/%Y")
y
[1] "01/01/2000"

str(y)
chr "01/01/2000"

y <- strftime(x = x,format = "%m/%d/%Y")
y
[1] "01/01/2000"

str(y)
chr "01/01/2000"

Upvotes: 1

Related Questions