user1605665
user1605665

Reputation: 4151

How can I reformat a series of dates in a vector in R

I have vector of dates that i'm trying to convert with as date but i'm not getting the expected output, when I sapply with as.Date instead of getting a series of reformatted dates I get the names as dates and some odd value.

dates = c("20-Mar-2015", "25-Jun-2015", "23-Sep-2015", "22-Dec-2015")
sapply(dates, as.Date, format = "%d-%b-%Y")
20-Mar-2015 25-Jun-2015 23-Sep-2015 22-Dec-2015 
      16514       16611       16701       16791 

I would like each of the values in the vector to be showing the new formated value. E.g. like what would happen if as.Date was shown applied to each element

as.Date("20-Mar-2015", format = "%d-%b-%Y")
[1] "2015-03-20"

Upvotes: 0

Views: 145

Answers (1)

user3710546
user3710546

Reputation:

You can directly use as.Date(dates, format = "%d-%b-%Y"). as.Date is vectorized, i.e. it can take a vector as input, not only a single entry.

In your case:

dates <- c("20-Mar-2015", "25-Jun-2015", "23-Sep-2015", "22-Dec-2015")
as.Date(dates, format = "%d-%b-%Y")
# [1] "2015-03-20" "2015-06-25" "2015-09-23" "2015-12-22"

Upvotes: 1

Related Questions