2015-10-29 28 views
1

我想基於時間子集數據幀:你如何子集的數據幀基於小時,分鐘,秒鐘的最有效的方式

df 

Hostname Date cpu 
Server101 1/1/2015 00:00:00 10 
Server101 1/1/2015 00:00:00 10 
Server101 1/1/2015 08:00:00 10 
Server101 1/1/2015 06:00:00 10 

我需要從09:00獲取數據: 00至17:00:00

所以這是我做的:

library(lubridate) 
df<-transform(df, time= format(df$Date,'%H:%M:%S')) 
df$time<-times(df$time) 

df<-subset(df, time>times(c("09:00:00")) & time<times(c("17:00:00""))) 

子功能的子集基於時間走的是一條很長的時間才能完成。有沒有更好的方法來做到這一點,最快?

+0

你是否在格式化步驟之前轉換爲'Date'類 – akrun

+0

@akrun,是日期是as.POSIXct – user1471980

+0

數據集有多大 – akrun

回答

3

你可能要考慮data.tableITime類(這是基於POSIXlt)。或許,這將是最快的選擇:

數據:

df <- read.table(header=T, text="Hostname Date cpu 
Server101 '1/1/2015 00:00:00' 10 
Server101 '1/1/2015 00:00:00' 10 
Server101 '1/1/2015 08:00:00' 10 
Server101 '1/1/2015 10:00:00' 10") 

解決方案:

library(data.table) 
df$Date <- as.POSIXct(df$Date, format='%d/%m/%Y %H:%M:%S') 
#setDT coverts the df to a data.table 
#as.ITime converts the date to an ITime class 
#in the last chain you subset the data table 
setDT(df)[,time:=as.ITime(Date)][time>=as.ITime('09:00:00') & time<=as.ITime('17:00:00')] 

在您的示例數據集(只是改變了最後一排得到的結果):

setDT(df)[,time:=as.ITime(Date)][time>=as.ITime('09:00:00') & time<=as.ITime('17:00:00')] 
    Hostname    Date cpu  time 
1: Server101 2015-01-01 10:00:00 10 10:00:00 
相關問題