从Zoo :: yearmon对象中提取月份和年份

我有一个yearmon对象:


require(zoo)

date1 <- as.yearmon("Mar 2012", "%b %Y")

class(date1)

# [1] "yearmon"

如何从中提取月份和年份?


month1 <- fn(date1)

year1 <- fn(date1)

我应该用什么功能代替 fn()


哔哔one
浏览 1221回答 3
3回答

喵喔喔

将format()方法用于class对象"yearmon"。这是您的示例日期(正确创建!)date1 <- as.yearmon("Mar 2012", "%b %Y")然后,我们可以根据需要提取日期部分:> format(date1, "%b") ## Month, char, abbreviated[1] "Mar"> format(date1, "%Y") ## Year with century[1] "2012"> format(date1, "%m") ## numeric month[1] "03"这些作为字符返回。as.numeric()如果希望将年份或数字月份作为数字变量,请在适当的地方包装,例如> as.numeric(format(date1, "%m"))[1] 3> as.numeric(format(date1, "%Y"))[1] 2012请参阅?yearmon和,?strftime以获取详细信息-后者解释了可以使用的占位符。

青春有我

该lubridate包是令人惊叹的这种事情:> require(lubridate)> month(date1)[1] 3> year(date1)[1] 2012
打开App,查看更多内容
随时随地看视频慕课网APP