2015-05-19 21 views
1

我是R的新手,所以這可能是一個簡單的問題,但它給我帶來了很多困難。在R中的多個數據幀中設置日期和時間

我想跨數據框中找到的兩個值之間的子集,我試圖在這兩個值之間的子集時遇到困難。我將首先描述我已經完成的工作,正在工作的工作,然後是什麼不工作。

我有兩個數據幀。一個有一系列風暴數據,包括風暴事件的日期,另一個有一系列數據,對應於成千上萬次監測事件的排放。我試圖查看是否有任何排放數據在風暴事件開始和結束日期/時間內相對應。

我所做的迄今如下:

例出院數據:

X. DateTime  Depth DateTime1   newcol 
1 3 8/2/2013 13:15 0.038 2013-08-02 13:15:00 1375463700 
2 4 8/2/2013 13:30 0.038 2013-08-02 13:30:00 1375464600 
3 5 8/2/2013 13:45 0.039 2013-08-02 13:45:00 1375465500 
4 6 8/2/2013 14:00 0.039 2013-08-02 14:00:00 1375466400 

例風暴數據:

Storm newStart newEnd 
1 1 1382125500 1382130000 
2 2 1385768100 1385794200 

#Make a value to which the csv files are attached 
CA_Storms <- read.csv(file = "CA_Storms.csv", header = TRUE, stringsAsFactors = FALSE) 
CA_adj <- read.csv(file = "CA_Adj.csv", header = TRUE, stringsAsFactors = FALSE) 

#strptime function (do this for all data sets) 
CA_adj$DateTime1 <- strptime(CA_adj$DateTime, format = "%m/%d/%Y %H:%M") 
CA_Storms$Start.time1 <- strptime(CA_Storms$Start.time, format = "%m/%d/%Y %H:%M") 
CA_Storms$End.time1 <- strptime(CA_Storms$End.time, format = "%m/%d/%Y %H:%M") 

#Make dates and times continuous 
CA_adj$newcol <- as.numeric(CA_adj$DateTime1) 
CA_Storms$newStart <- as.numeric(CA_Storms$Start.time1) 
CA_Storms$newEnd <- as.numeric(CA_Storms$End.time1) 

這讓我成功地做到以下子集:

CA_adj[CA_adj$newcol == "1375463700", ] 

Example output: 
X.  DateTime Depth   DateTime1  newcol 
    1 3 8/2/2013 13:15 0.038 2013-08-02 13:15:00 1375463700 

CA_adj[CA_adj$newcol == CA_Storms[1,19], ] 

X.  DateTime   Depth DateTime1   newcol 
7403 7408 10/18/2013 15:45 0.058 2013-10-18 15:45:00 1382125500 

CA_adj[CA_adj$newcol <= CA_Storms[1,20], ] 

然而,每當我試圖把它的兩個值,如之間移動:

CA_adj[CA_adj$newcol >= CA_Storms[1,19] & CA_adj$newol <= CA_Storms[1,20], ]

其與此迴應:

[1] X.  DateTime Depth  DateTime1 newcol 
<0 rows> (or 0-length row.names) 

我知道這個輸出是不正確,因爲,通過通過我的大型數據集粗略查看,至少存在一個符合這些標準的值。

什麼給?

+0

請發佈樣本數據和期望的輸出。 – Soheil

+0

不是'CA_adj [CA_adj $ newcol> = CA_Storms [1,19] | CA_adj $ newol <= CA_Storms [1,20],]'你想要什麼? – Robert

+0

@Sheheil謝謝你的建議。我編輯了這篇文章,現在添加了這些內容。 –

回答

0
discharge<-data.frame(x=c(3,4,5,6), 
         DateTime=c("8/2/2013 13:15","8/2/2013 13:30", 
            "8/2/2013 13:45","8/2/2013 14:00"), 
         Depth=c(0.038, 0.038, 0.039, 0.039) 
        ) 
discharge$DateTime1<- as.POSIXct(discharge$DateTime, format = "%m/%d/%Y %H:%M") 

storm<-data.frame(storm=c(1,2), 
        start=c("8/2/2013 13:15","8/2/2013 16:30"), 
        end=c("8/2/2013 13:45","8/2/2013 16:45") 
       ) 

storm$start<- as.POSIXct(storm$start, format = "%m/%d/%Y %H:%M") 
storm$end<- as.POSIXct(storm$end, format = "%m/%d/%Y %H:%M") 


discharge[(discharge$DateTime1>=storm[1,2] & discharge$DateTime1<=storm[1,3]),]