T Richard
T Richard

Reputation: 601

How to retain month/year from the day/month/year date format using R

There is an excel file containing dates in the form day/month/year. I want to retain the month and the year in the form month/year using R.

I have tried by making use of the function "format" as below:

date = c("2/8/2018","22/11/2018","1/2/2019")
n.date <- format(as.Date(date), "%m/%Y")

It gives:

n.date
[1] "08/0002" "11/0022" "02/0001"

However, I expect to have something like

"8/2018" "11/2018" "2/2019".

Please, how do I go about this. Any help is greatly appreciated.

Upvotes: 1

Views: 201

Answers (2)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 522817

You should be using the format option in your call to as.Date, when you parse the strings into dates, with the mask %d/%m/%Y. Then, call format() with the month-year mask you want:

date = c("2/8/2018", "22/11/2018", "1/2/2019")
n.date <- as.Date(date, format="%d/%m/%Y")

format(n.date, "%m/%Y")

[1] "08/2018" "11/2018" "02/2019"

To remove the leading zeroes:

output <- format(n.date, "%m/%Y")
output <- sub("^0*", "", output)
output

[1] "8/2018"  "11/2018" "2/2019"

Upvotes: 2

Ronak Shah
Ronak Shah

Reputation: 389355

If you check as.Date(date) it doesn't give you correct dates. So usually the answer by @Tim is the way to go however, you can also use regex to achieve your desired result here

sub("\\d+/", "", date)
#[1] "8/2018"  "11/2018" "2/2019" 

This deletes a number followed by "/" in date.

Upvotes: 1

Related Questions