简体   繁体   中英

R: Convert month and 2 digit year into date

How can this date string be converted in R and lubridate ?

lubridate::as_date('Apr-78', format = '%B-%Y')

How to prevent the error invalid 'tz' ?

lubridate::parse_date_time("Apr-78", 'my')

Others have already mentioned that your format isn't quite correct, so watch out for that. As far as timezones are concerned: My first thought was that you simply need to add tz = "UTC" (or some other timezone), but the fact that your date has no day information is the bigger issue. If you don't address this then adding a timezone via tz will simply yield NA . There are a couple of easy methods to deal with this. You could simply paste an arbitrary day onto your dates, but you can simplify things even more by using readr::parse_date , which will default to first day of the month. You can then extract your month and year from the resultant date and then drop the date, for example:

library(tidyverse)
library(lubridate)

parse_date("Apr-78", "%b-%y") %>% 
    tibble(date = ., year = year(date), month = month(date)) %>% 
    select(-date)

Which will give you two variables for the year and month:

# A tibble: 1 x 2
   year month
  <dbl> <dbl>
1  1978     4

You could also keep the date instead of extracting the year and month, but that might get confusing down the road - ie someone might thing something happened on April 1, 1978, and not in April, 1978. You will probably group by years and/or months anyway, so it makes sense to turn them into variables.

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