I have tried a number of methods to no avail. I have data in terms of a date (YYYY-MM-DD) and am trying to get in terms of just the month and year, such as: MM-YYYY or YYYY-
Here's another solution using a package solely dedicated to working with dates and times in R:
library(tidyverse)
library(lubridate)
(df <- tibble(ID = 1:3, Date = c("2004-02-06" , "2006-03-14", "2007-07-16")))
#> # A tibble: 3 x 2
#> ID Date
#> <int> <chr>
#> 1 1 2004-02-06
#> 2 2 2006-03-14
#> 3 3 2007-07-16
df %>%
mutate(
Date = ymd(Date),
Month_Yr = format_ISO8601(Date, precision = "ym")
)
#> # A tibble: 3 x 3
#> ID Date Month_Yr
#> <int> <date> <chr>
#> 1 1 2004-02-06 2004-02
#> 2 2 2006-03-14 2006-03
#> 3 3 2007-07-16 2007-07
Created on 2020-09-01 by the reprex package (v0.3.0)
Use substring?
d = "2004-02-06"
substr(d,0,7)
>"2004-02"
This will add a new column to your data.frame
with the specified format.
df$Month_Yr <- format(as.Date(df$Date), "%Y-%m")
df
#> ID Date Month_Yr
#> 1 1 2004-02-06 2004-02
#> 2 2 2006-03-14 2006-03
#> 3 3 2007-07-16 2007-07
# your data sample
df <- data.frame( ID=1:3,Date = c("2004-02-06" , "2006-03-14" , "2007-07-16") )
a simple example:
dates <- "2004-02-06"
format(as.Date(dates), "%Y-%m")
> "2004-02"
side note:
the data.table
approach can be quite faster in case you're working with a big dataset.
library(data.table)
setDT(df)[, Month_Yr := format(as.Date(Date), "%Y-%m") ]
The data.table
package introduced the IDate
class some time ago and zoo
-package-like functions to retrieve months, days, etc (Check ?IDate
). so, you can extract the desired info now in the following ways:
require(data.table)
df <- data.frame(id = 1:3,
date = c("2004-02-06" , "2006-03-14" , "2007-07-16"))
setDT(df)
df[ , date := as.IDate(date) ] # instead of as.Date()
df[ , yrmn := paste0(year(date), '-', month(date)) ]
df[ , yrmn2 := format(date, '%Y-%m') ]