Reputation: 11934
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'
?
Upvotes: 2
Views: 993
Reputation:
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.
Upvotes: 0