R: Convert month and 2 digit year into date

你说的曾经没有我的故事 提交于 2019-12-24 07:35:25

问题


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'?


回答1:


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



回答2:


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 - i.e. 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.



来源:https://stackoverflow.com/questions/57925731/r-convert-month-and-2-digit-year-into-date

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!