GCGM
GCGM

Reputation: 1073

Convert dates to text in R

I have the following dataset with dates (YYYY-MM-DD):

> dates
 [1] "20180412" "20180424" "20180506" "20180518" "20180530" "20180611" "20180623" "20180705" "20180717" "20180729"

I want to convert them in: DD-MMM-YYYY but with the month being text. For example 20180412 should become 12Apr2018

Any suggestion on how to proceed?

M

Upvotes: 7

Views: 9034

Answers (4)

Saurabh Chauhan
Saurabh Chauhan

Reputation: 3221

Simply use as.POSIXct and as.format:

dates <- c("20180412", "20180424", "20180506")
format(as.POSIXct(dates, format="%Y%m%d"),format="%d%b%y")

Output:

[1] "12Apr18" "24Apr18" "06May18"

Upvotes: 3

forestfanjoe
forestfanjoe

Reputation: 412

You could use the as.Date() and format() functions:

dts <- c("20180412", "20180424", "20180506", "20180518", "20180530", 
         "20180611", "20180623")

format(as.Date(dts, format = "%Y%m%d"), "%d%b%Y")

More information here

Upvotes: 3

TOAN TRAN
TOAN TRAN

Reputation: 61

You can try something like this :

# print today's date
today <- Sys.Date()
format(today, format="%B %d %Y") "June 20 2007"

where The following symbols can be used with the format( ) function to print dates 1

Upvotes: 6

Dirk is no longer here
Dirk is no longer here

Reputation: 368429

You need to first parse the text strings as Date objects, and then format these Date objects to your liking to have the different text output:

R> library(anytime)   ## one easy way to parse dates and times
R> dates <- anydate(c("20180412", "20180424", "20180506", "20180518", "20180530",
+                    "20180611", "20180623", "20180705", "20180717", "20180729"))
R> dates
 [1] "2018-04-12" "2018-04-24" "2018-05-06" "2018-05-18" "2018-05-30"
 [6] "2018-06-11" "2018-06-23" "2018-07-05" "2018-07-17" "2018-07-29"
R> 
R> txtdates <- format(dates, "%d%b%Y")
R> txtdates
 [1] "12Apr2018" "24Apr2018" "06May2018" "18May2018" "30May2018"
 [6] "11Jun2018" "23Jun2018" "05Jul2018" "17Jul2018" "29Jul2018"
R> 

Upvotes: 5

Related Questions