PeatyBoWeaty
PeatyBoWeaty

Reputation: 31

R Convert number to month

I'm trying to build a time series. My data frame has each month listed as a number. When I use as.Date() I get NA. How do I convert a number to its respective month, as a date.

Example

Upvotes: 1

Views: 2748

Answers (2)

G. Grothendieck
G. Grothendieck

Reputation: 270298

Below we assume that the month numbers given are the number of months relative to a base of the first month so for example month 13 would represent 12 months after month 1. Also we assume that the months re unique since that is the case in the question and since it is stated there that it represents a time series.

1) Let base be the year and month as a yearmon class object identifying the base year/month and assume months is vector of month numbers such that 1 is the base, 2 is one month later and so on. Since yearmon class represents a year and month as year + 0 for Jan, year + 1/12 for Feb, ..., year + 11/12 for Dec we have the code below to get a Date vector. Alternately use ym instead since that models a year and month already.

library(zoo)
# inputs    
base <- as.yearmon("2020-01")
months <- 1:9

ym <- base + (months-1)/12
as.Date(ym)
## [1] "2020-01-01" "2020-02-01" "2020-03-01" "2020-04-01" "2020-05-01"
## [6] "2020-06-01" "2020-07-01" "2020-08-01" "2020-09-01"

For example, if we have this data.frame we can convert that to a zoo series or a ts series like this using base from above:

library(zoo)
DF <- data.frame(month = 1:9, value = 11:19) # input

z <- with(DF, zoo(value, base + (month-1)/12)) # zoo series
tt <- as.ts(z) # ts series

2) Alternately, if it were known that the series is consecutive months starting in January 2020 then we could ignore the month column and do this (where DF and base were shown above):

library(zoo)

zz <- zooreg(DF$value, base, freq = 12) # zooreg series
as.ts(zz) # ts series

3) This would also work to create a ts series if we can make the same assumptions as in (2). This uses only base R.

ts(DF$value, start = 2020, freq = 12)

Upvotes: 0

Daniel_j_iii
Daniel_j_iii

Reputation: 3252

R Base has a built in month dataset. make sure your numbers are actually numeric by as.numeric() and then you can just use month.name[1] which outputs January

Upvotes: 1

Related Questions