Wayne Yang
Wayne Yang

Reputation: 1

How do I combine Month and Year into a single column in R

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

Answers (2)

G. Grothendieck
G. Grothendieck

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

Andres
Andres

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

Related Questions