Reputation: 1
I'd like to use the zoo library and and specifically the as.yearmon function as follows:
df$YearMonth <- as.yearmon(paste(df$year, df$month), "%Y %m")
However, the resulting "YearMonth" column showed NA for the column. Do you know what is going wrong? Is it possible that it is due to the month and year variable in my data being a factor and integer respectively?
Upvotes: 0
Views: 4567
Reputation: 269461
Your code should work if you have appropriate inputs. For example, all these work:
library(zoo)
yr <- 2001:2003
mo <- 1:3
as.yearmon(paste(yr, " ", mo), format = "%Y %m")
## [1] "Jan 2001" "Feb 2002" "Mar 2003"
as.yearmon(paste(yr, mo), format = "%Y %m")
## [1] "Jan 2001" "Feb 2002" "Mar 2003"
as.yearmon(paste0(yr, " ", mo), format = "%Y %m")
## [1] "Jan 2001" "Feb 2002" "Mar 2003"
as.yearmon(paste(yr, mo, sep = "-"))
## [1] "Jan 2001" "Feb 2002" "Mar 2003"
as.yearmon(paste0(yr, "-", mo))
## [1] "Jan 2001" "Feb 2002" "Mar 2003"
as.yearmon(yr + (mo - 1)/12)
## [1] "Jan 2001" "Feb 2002" "Mar 2003"
Upvotes: 1
Reputation: 2493
You have to match what is inside paste()
with the format argument "%Y %m"
like this:
df$YearMonth <- as.yearmon(paste(df$year, " ", df$month), "%Y %m")
Upvotes: 1