2011-07-01 81 views
8

不同列我有一個看起來像動物園的對象:拆分日期爲年,月和

頭(OBS)

 Index pp 
1932-01-01 0 
1932-01-02 0.2 
1932-01-03 0 

,我想索引分成3列(年,幾個月和幾天在不同的列),所以我可以使用ddply每月的一天進行一些分析。

我不知道這有什麼差別,但使用創建我的日期:

dates <- as.Date(CET[,1], "%d-%m-%Y") 
obs <- xts(CET[,2], dates) 

其中CET是在第1列和第日期列中的原始文件2

謝謝幫助!

回答

16

1)。我們可以使用lubridate的year/month/day或節段性month.day.year

1A)通過代上通過lubridate

​​

1B)

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))) 

2) 。但是,我們並不需要首先創建列。我們可以只使用aggregate.zoo直接與原動物園對象,z,使用lubridate或克隆氏病或取決於它是什麼,你想要做的只是用yearmon從動物園:

2A)骨料使用lubridate

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)中骨料使用克隆氏病

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) 

2C)骨料使用yearmon

如果我們希望每年/月均月月總結,而不是結塊所有一月月在一起,在一起,等於是我們既不需要代上也不lubridate而是可以使用動物園的yearmon

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

aggregate(z, yearmon, mean) 
5

你可以試試:

CET$year <- format(CET[,1], "%Y") # year 
CET$month <- format(CET[,1], "%m") # month 
CET$day <- format(CET[,1], "%d") # day 
+1

感謝,但它不工作:'錯誤format.default(結構(as.character(X),名稱=名稱(X),昏暗朦朧=(X): 無效 '修剪'參數' – sbg

+2

看起來你的日期是因素。你可以使用str()函數來確保你的日期實際上是日期。 –

7
dtstr <- as.character(index(CET)) 

CET$yr <- sapply(strsplit(dtstr, "-") , "[", 1) 
CET$mon <- sapply(strsplit(dtstr, "-") , "[", 2) 
CET$dt <- sapply(strsplit(dtstr, "-") , "[", 3) 
+0

謝謝德文,索引(CET)'不起作用('錯誤:找不到函數「索引」',但改爲'dtstr < - as.character(CET [,1])',工作! – sbg

+1

很高興有你需要的地方。注意:函數拼寫爲'index',而不是'Index' –

2
require(lubridate) 
maindata1 <- cbind(maindata1, day=day(maindata1$Date), month=month(maindata1$date), year=year(maindata1$date)) 
+1

請添加一些關於代碼的說明,而不僅僅是代碼轉儲。 –