我想使用zoo库,特别是as.yearmon函数,如下所示:
df$YearMonth <- as.yearmon(paste(df$year, df$month), "%Y %m")
然而,由此产生的&#34; YearMonth&#34;柱显示该柱的NA。你知道出了什么问题吗?是否可能是由于我的数据中的月份和年份变量分别是因子和整数?
答案 0 :(得分:1)
您必须将paste()
内的内容与格式参数"%Y %m"
匹配,如下所示:
df$YearMonth <- as.yearmon(paste(df$year, " ", df$month), "%Y %m")
答案 1 :(得分:0)
如果您有适当的输入,您的代码应该有用。例如,所有这些工作:
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"