日期转换为.yearmon

问题描述 投票:0回答:1

我有一个看起来像这样的数据框:

library(zoo)
head(monthly.station6)

                    [,1]
1995-02-28 00:00:00 2.07
1995-03-01 00:00:00 5.70
1995-04-30 01:00:00 0.65
1995-05-31 01:00:00 1.03
1995-06-30 01:00:00 0.77
1995-07-31 01:00:00 0.39

我正在应用此代码:

monthly.station6[,0] <- as.yearmon(monthly.station6[,0])
尝试将其转换为年月格式,但我认为日期列为 [,0] 的事实阻止了它?不确定我哪里出错了,任何帮助将不胜感激!

head(monthly.station6)

             [,1]
Feb 1995 2.07
Mar 1995 5.70
Apr 1995 0.65
May 1995 1.03
Jun 1995 0.77
Jul 1995 0.39

根据要求

dput(head(monthly.station6))

structure(c(2.07, 5.7, 0.65, 1.03, 0.77, 0.39), .indexCLASS = c("POSIXct", 
"POSIXt"), .indexTZ = "", tclass = c("POSIXct", "POSIXt"), tzone = "", class = c("xts", 
"zoo"), index = structure(c(793929600, 794016000, 799200000, 
801878400, 804470400, 807148800), tzone = "", tclass = c("POSIXct", 
"POSIXt")), .Dim = c(6L, 1L))
r date date-conversion
1个回答
0
投票

1) index 对象的类是

"xts"
,而不是
"data.frame"
。使用
index
(或
time
)修改
monthly.station6

library(xts)
index(monthly.station6) <- as.yearmon(index(monthly.station6))

2) aggregate.zoo 另一种可能性是使用

aggregate.zoo
。这将返回一个
"zoo"
对象,因此将其转换回
"xts"
:

library(xts)
as.xts(aggregate(monthly.station6, as.yearmon))

3) fortify.zoo 由于问题提到了 data.frame,如果您真正想要的是 data.frame,那么

library
之后的第一个语句将创建一个 data.frame,其第一列为
Index
和第二个将执行转换为
"yearmon"

library(xts)
DF <- fortify.zoo(monthly.station6)
transform(DF, Index = as.yearmon(Index))

注意: 如果你只想要年份,那么它不能是一个 xts 对象,但你可以将它表示为一个 data.frame。使用 (3) 中的

DF

transform(DF, Index = as.numeric(format(Index, "%Y")))
© www.soinside.com 2019 - 2024. All rights reserved.