R 将日期拆分为年、月和日的不同列

R 将日期拆分为年、月和日的不同列,r,date,R,Date,我有动物园里的东西,看起来像: 主管(obs) 我想将索引分为3列(年、月和日在单独的列中),这样我就可以使用ddply每月每天进行一些分析 我不知道这是否有什么区别,但我的日期是通过以下方式创建的: dates <- as.Date(CET[,1], "%d-%m-%Y") obs <- xts(CET[,2], dates) 日期您可以尝试: CET$year <- format(CET[,1], "%Y") # year CET$month <- format(C

我有动物园里的东西,看起来像:

主管(obs)

我想将索引分为3列(年、月和日在单独的列中),这样我就可以使用
ddply
每月每天进行一些分析

我不知道这是否有什么区别,但我的日期是通过以下方式创建的:

dates <- as.Date(CET[,1], "%d-%m-%Y")
obs <- xts(CET[,2], dates)
日期您可以尝试:

CET$year <- format(CET[,1], "%Y") # year
CET$month <- format(CET[,1], "%m") # month
CET$day <- format(CET[,1], "%d") # day
CET$year
dtstr1)。我们可以使用lubridate的
/
/
或chron的
月.日.年

1a)通过lubridate

library(zoo)
z <- zoo(1:1000, as.Date("1932-01-01") + 0:999)

library(lubridate)
tt <- time(z)
zz <- cbind(z, year = year(tt), month = month(tt), day = day(tt))
library(zoo)
z <- zoo(1:1000, as.Date("1932-01-01") + 0:999)

library(lubridate)
aggregate(z, day, mean)
aggregate(z, month, mean)
aggregate(z, year, mean)
2b)使用chron进行聚合

library(zoo)
z <- zoo(1:1000, as.Date("1932-01-01") + 0:999)

library(chron)
zz <- with(month.day.year(time(z)), zoo(cbind(z, day, month, year)))
library(zoo)
z <- zoo(1:1000, as.Date("1932-01-01") + 0:999)

library(chron)
mdy <- month.day.year(time(z))

aggregate(z, mdy$day, mean)
aggregate(z, mdy$month, mean)
aggregate(z, mdy$year, mean)

# or
ct <- as.chron(time(z))

aggregate(z, days(ct), mean)
aggregate(z, months(ct), mean)
aggregate(z, years(ct), mean)

# days(ct) and years(ct) can actually
# be shortened to just days and years within the above context
# (and that would work for months too except they would be out of order)
aggregate(z, days, mean)
aggregate(z, years, mean)
require(润滑油)

maindat1谢谢,但它不起作用:
格式错误。默认(结构:as.character(x),names=names(x),dim=dim(x),:无效的'trim'参数
似乎日期是因数。您可以使用str()函数确保日期实际上是日期。谢谢,DWin,
索引(CET)
不起作用(
错误:找不到函数“Index”
),但更改为
dtstr很高兴它能满足您的需要。注意:函数拼写为
Index
,而不是
Index
。请添加一些关于代码的解释,而不仅仅是代码转储。
library(zoo)
z <- zoo(1:1000, as.Date("1932-01-01") + 0:999)

library(lubridate)
aggregate(z, day, mean)
aggregate(z, month, mean)
aggregate(z, year, mean)
library(zoo)
z <- zoo(1:1000, as.Date("1932-01-01") + 0:999)

library(chron)
mdy <- month.day.year(time(z))

aggregate(z, mdy$day, mean)
aggregate(z, mdy$month, mean)
aggregate(z, mdy$year, mean)

# or
ct <- as.chron(time(z))

aggregate(z, days(ct), mean)
aggregate(z, months(ct), mean)
aggregate(z, years(ct), mean)

# days(ct) and years(ct) can actually
# be shortened to just days and years within the above context
# (and that would work for months too except they would be out of order)
aggregate(z, days, mean)
aggregate(z, years, mean)
library(zoo)
z <- zoo(1:1000, as.Date("1932-01-01") + 0:999)

aggregate(z, yearmon, mean)
require(lubridate)
maindata1 <- cbind(maindata1, day=day(maindata1$Date), month=month(maindata1$date), year=year(maindata1$date))