2013-08-30 55 views
0

我無法找到我的POSIXct格式問題的解決方案 - 我有一個月度數據。這是我的代碼廢料:回顧日期POSIXct

Data <- as.POSIXct(as.character(czerwiec$Data), format = "%Y-%m-%d %H:%M:%S") 
get.rows <- Data >= as.POSIXct(as.character("2013-06-03 00:00:01")) & Data <= as.POSIXct(as.character("2013-06-09 23:59:59")) 
czerwiec <- czerwiec[get.rows,] 
Data <- Data[get.rows] 

我選擇了一個孔周月3〜9,並希望通過每一個小時來估計列X(czerwiec$X)的總和。正如你看到的,我可以減少時間,但它會愚蠢到去做,這樣

get.rows <- Data >= as.POSIXct(as.character("2013-06-03 00:00:01")) & 
    Data <= as.POSIXct(as.character("2013-06-03 00:59:59")) 

然後

get.rows <- Data >= as.POSIXct(as.character("2013-06-04 00:00:01")) & 
    Data <= as.POSIXct(as.character("2013-06-04 00:59:59")) 

而在此操作結束後,我可以估計總和這一小時等

你有什麼想法,我怎麼記得每一行,有時間2013-06-03到2013-06-09和00:00:01到00:59:59我有三列,第一個叫「ID」,第二個叫「價格」,第三個叫「數據」(意思是日期)。

Thx for help :)

+1

請添加代碼,使我們能夠再現數據幀'czerwiec '。 –

+0

德魯斯滕,你有足夠的信息來幫助我嗎? Thx提前:) – Blazej

+0

請參閱http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example關於如何製作可重現的示例 - 這將有助於SO用戶更好地理解你的數據是什麼以及你想用它們做什麼 –

回答

0

這可能有所幫助。我用lubridate包,它並沒有真正做任何事情,你不能在基礎R做的,但它使處理日期更加容易

# Set up Data as a string vector 
Data <- c("2013-06-01 05:05:05", "2013-06-06 05:05:05", "2013-06-06 08:10:05", "2013-07-07 05:05:05") 

require(lubridate) 

# Set up the data frame with fake data. This makes a reproducible example 
set.seed(4) #For reproducibility, always set the seed when using random numbers 

# Create a data frame with Data and price 
czerwiec <- data.frame(price=runif(4)) 

# Use lubridate to turn the Data string into a vector of POSIXctn objects 
czerwiec$Data <- ymd_hms(Data) 

# Determine the 'yearday' -i.e. yearday of Jan 1 is 1; yearday of Dec 31 is 365 (or 366 in a leap year) 
czerwiec$yday <- yday(czerwiec$Data) 

# in.range is true if the date is in the desired date range 
czerwiec$in.range <- czerwiec$yday[czerwiec$yday >= yday(ymd("2013-06-03")) & 
            czerwiec$yday yday(ymd("2013-06-09")] 

# Pick out the dates that have the range that you want 
selected_dates <- subset(czerwiec, in.range==TRUE)