0

I have a bunch of dates in a df column in the following format: dd.mm.yyyy

I want it to look like this: 01/2020 (mm.yyyy)

How can I remove the day from all of the dates?

sjoelly
  • 147
  • 2
  • 11
  • 3
    Does this answer your question? [Format Date to Year-Month in R](https://stackoverflow.com/questions/50338191/format-date-to-year-month-in-r) – mnist Apr 30 '20 at 21:24

4 Answers4

5

Use format to specify the date format you'd like

date <- as.Date("13/01/2020", format = "%d/%m/%Y")
format(date, "%m/%Y")
[1] "01/2020"

Edit - applying to dataframe column

dates <- c("13/01/2020", "17/02/2015", "13/03/2013")
df <- data.frame(dates, stringsAsFactors = FALSE)
df$dates <- as.Date(df$dates, format = "%d/%m/%Y")
df$dates_format <- format(df$dates, "%m/%Y")
df
       dates dates_format
1 2020-01-13      01/2020
2 2015-02-17      02/2015
3 2013-03-13      03/2013
Greg
  • 3,570
  • 5
  • 18
  • 31
  • I have a lot of different dates in the column, so this code only changes dates matching 13/01/2020, is there any way to make it applicable to all dates in the column?? – sjoelly Apr 30 '20 at 21:30
  • @sjoelly - yes, see edit – Greg Apr 30 '20 at 21:35
2

Besides format by @Greg, another option is using sub like below

> sub(".*?/","","13/01/2020")
[1] "01/2020"
ThomasIsCoding
  • 96,636
  • 9
  • 24
  • 81
2

Here is a solution using lubridate.

library(lubridate)

#Set the desired format (mm-yyyy) as my_stamp
my_stamp<-stamp( "02-2019", 
                 orders = "my") 

#A df with a column full of dates
df <- data.frame(dates = c("30/04/2020","29/03/2020","28/02/2020"))

#Change the column from string to date format
df$dates<-dmy(df$dates)

#Apply the format you desire to the dates (i.e., only month and year)
df$dates<-my_stamp(df$dates)

#    dates
#1 04-2020
#2 03-2020
#3 02-2020
0

There are explicit date formatting options in R (see answer by Greg). Another option would be to separate the date into 3 columns, and then recombine the month and year, putting a / in between. Note this leaves the new date column in character format, which you may want to change depending on your needs.

library(tidyr)
df <- data.frame(date = "13/01/2020")
df <- separate(df, date, into = c("day","month","year"), sep = "/")
df$newdate <- paste(df$month, df$year, sep = "/")