Reputation: 51
I hope you guys are having a good night.
I have a dataset that looks something like this:
data1
[date] [fuel_price]
[1,] 201004 3.56
[2,] 201105 3.32
[3,] 201106 3.45
[4,] 201212 3.94
[4,] 201301 3.94
The dates are in the format of: YYYYMM, and I'm trying to have R interpret it that way. Here is my code so far:
DateNum = as.numeric(as.POSIXct(data1$date, format="%Y%m"))
PriceFun = approxfun(thedata1$fuel_price ~ DateNum)
PriceFromDate = function(x) {
round(PriceFun(x), 3) }
Any reason why it isn't working for me?
Thank you guys in advanced.
Upvotes: 2
Views: 45
Reputation: 18585
It's rather risky approach but you could consider making use of the anytime
package:
x <- c(201004,
201105,
201106,
2012012,
201301)
anytime::anytime(x, asUTC = TRUE)
this would give you:
[1] "2010-04-01 01:00:00 BST" "2011-05-01 01:00:00 BST" "2011-06-01 01:00:00 BST"
[4] "2012-12-01 00:00:00 GMT" "2013-01-01 00:00:00 GMT"
The points discussed in comments are valid, you may first prefer to arrive at unambiguous strings making conscious assumptions about the date format; like assuming first day of a month for each date and the undertaking your conversions; the provided solutions uses your initial string 2012012
with typo to demonstrate that anytime would manage this string as well.
Upvotes: 1