How to convert a string such as 20100502 into date format %m/%d/%Y
I tried to convert using
as.Date(20100502, origin="1970-01-01", format = "%Y-%m-%d") But, the result is "57003-04-23" instead of 05/02/2010
You can use as.Date and format
format(as.Date("20100502", format = "%Y%m%d"), "%m/%d/%Y") #[1] "05/02/2010" The format argument in as.Date refers to the format in which you provide your data to the function. Then in the function format you provide the format that you desire.
from ?as.Date
as.Date will accept numeric data (the number of days since an epoch), but only if origin is supplied.
A workaround as suggested by @Wimpel in comments is to wrap x in as.character.
X$new_Date <- format(as.Date(as.character(X$Date), format = "%Y%m%d"), "%m/%d/%Y") dput(head(X$Date)) at the end of your question?X$Date has to be character-format. If not, make it so using as.character().
Dateobject and then back to a string with a different format. In the first step you have to specify the format of the input string (not the one you want eventually):x<-as.Date("20100502", format = "%Y%m%d"). Then withformatyou specify the output format:format(x,format="%m/%d/%Y").