1

I am trying to convert months in the following format:

histdata <- c("198001", "198002", "198003")

I tried:

histdata <- transform(histdata, date = as.Date(as.character(date), "%Y%m"))

but then all data turned to NA.

I would like to find a solution that will return a vector of dates instead.

Bulat
  • 6,869
  • 1
  • 29
  • 52
Ilias Geo
  • 9
  • 6

3 Answers3

0

You could try

convert_date <- function(x)
{
  x <- as.character(x)
  as.POSIXct(paste0(substr(x, 1, 4), "-", substr(x, 5, 6), "-01"))
}

So that you have:

convert_date(c(198002, 198003, 202001))
# [1] "1980-02-01 GMT" "1980-03-01 GMT" "2020-01-01 GMT"
Allan Cameron
  • 147,086
  • 7
  • 49
  • 87
0
library(readr)
ym <- c("198001", "198002", "198003")
parse_date(ym, format = "%Y%m")

or

library(readr)
ym <- c(198001, 198002, 198003)
parse_date(as.character(ym), format = "%Y%m")
Yuriy Saraykin
  • 8,390
  • 1
  • 7
  • 14
0

You can use base function as.Date with first day of the month added to your representation of the month:

as.Date(paste0(as.character(201901L), "01"), format = "%Y%m%d")
Bulat
  • 6,869
  • 1
  • 29
  • 52
  • But still in the data frame the format is the same when I hit str(histdata) and head(histdata) – Ilias Geo Jan 25 '20 at 19:47
  • I guess you just need to assign new values to the column in your data.frame – Bulat Jan 25 '20 at 19:51
  • Yes but your code replaces all dates in the column with the same data 2019 etc. – Ilias Geo Jan 25 '20 at 20:07
  • `as.Date(paste0(as.character(histdata), "01"), format = "%Y%m%d")` – Bulat Jan 25 '20 at 20:11
  • I just demonstrated that this works on one value, you can pass your vector and it should still work. Also have a look at answers on the other question, it might help. – Bulat Jan 25 '20 at 20:12