我有一個yearmon對象:require(zoo)date1 <- as.yearmon("Mar 2012", "%b %Y")class(date1)# [1] "yearmon"如何從中提取月份和年份?month1 <- fn(date1)year1 <- fn(date1)我應該用什么功能代替 fn()
3 回答

喵喔喔
TA貢獻1735條經驗 獲得超5個贊
將format()方法用于class對象"yearmon"。這是您的示例日期(正確創建?。?/p>
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以獲取詳細信息-后者解釋了可以使用的占位符。

青春有我
TA貢獻1784條經驗 獲得超8個贊
該lubridate包是令人驚嘆的這種事情:
> require(lubridate)
> month(date1)
[1] 3
> year(date1)
[1] 2012
- 3 回答
- 0 關注
- 1408 瀏覽
添加回答
舉報
0/150
提交
取消