如果我有一个示例数据帧:
Date <- c("05/12/2012 05:17:00", "05/12/2012 06:10:00", "05/12/2012 06:12:00", "05/12/2012 06:14:00",
"06/12/2012 05:25:00", "06/12/2012 06:55:00", "06/12/2012 06:19:00", "06/12/2012 08:00:00",
"07/12/2012 05:00:00", "07/12/2012 05:19:00", "07/12/2012 06:04:00",
"07/12/2012 06:59:00")
Date <- strptime(Date, "%d/%m/%Y %H:%M")
a <- sample(12)
hour <- as.numeric(format(Date, "%H"))
min <- as.numeric(format(Date, "%M")) / 60
hours_mins <- hour + min
df1 <- data.frame(Date,a,hour, min, hours_mins, stringsAsFactors = FALSE)
我希望能够在05:15到06:15之间保留数据帧的子集(仅在任何一天)。
我将小时和分钟转换为十进制变量,希望我能够做到这样的事情:
df1[df1$hours_mins >= '5.25' & df1$hours_mins < '6.25']
......但是这不起作用。有没有人有任何建议?
答案 0 :(得分:1)
删除引号并在最后添加逗号
df1[df1$hours_mins >= 5.25 & df1$hours_mins < 6.25,]
答案 1 :(得分:0)
实际上,POSIXlt对象的一个优点是它可以自动携带关键日期信息。
Date1 <- strptime(c("05/12/2012 05:17:00", "05/12/2012 06:10:00", "05/12/2012 06:12:00", "05/12/2012 06:14:00",
"06/12/2012 05:25:00", "06/12/2012 06:55:00", "06/12/2012 06:19:00", "06/12/2012 08:00:00",
"07/12/2012 05:00:00", "07/12/2012 05:19:00", "07/12/2012 06:04:00",
"07/12/2012 06:59:00"), "%d/%m/%Y %H:%M")
class(Date1)
a <- sample(12)
#please note since strptime() is used Date1 contains "hour", "min" etc
df1 <- data.frame(Date1, hr=Date1$hour, min=Date1$min, cum_hrs=Date1$min/60+Date1$hour, a, stringsAsFactors = FALSE)
df1[(df1$hr + df1$min/60>= 5.25) & (df1$hr + df1$min/60< 6.25),]
此外,如果您想要总小时数(十进制),我在数据框中添加了一列。我希望这能满足你的需求。