简体   繁体   中英

How to find year from year-month variable

I have a dataframe with a date vector. I would like to replace it with a year-month variable. I did so following the code below.

dates <- as.Date("2004-02-06")
ym <- format(dates, "%Y-%m")

I would like to be able to find the year (or month) using the ym variable but year(ym) and month(ym) don't work. How could I go about it?

They are no longer dates, so you have to use string functionality to fetch those numbers:


library(stringr)
m <- str_match( ym, "(\\d{4})-(\\d{2})" )
years <- m[,2]
months <- m[,3]

Try to use lubridate to get a date, and then use year or month function:

library(lubridate)

 parse_date_time(ym,orders = "ym")
 [1] "2004-02-01 UTC"

parse_date_time(ym,orders = "ym") %>%
  year()
[1] 2004

parse_date_time(ym,orders = "ym") %>%
  month()
[1] 2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM