2017-02-11 35 views
1

我有一个数据帧,它看起来像下面选择一个独特的基于时间的数据

"SERIAL_No.","DATE_","TIME_", 
"13606855","2011/08/02","14:15"    

因此,具有特定序列号一个人确实在一天中的不同时间某些活动,并有可用的数据为年。我想在上午5点之后选择与第一个条目相对应的单个条目。通过这种方式,我将为每个特定日期的每个序列号输入一个单独的条目。 我尝试以下,但我不知道这是否会工作:

df <- df[df$TIME_ >"5:00", ] 

但这5点后要选择所有条目。我不知道如何实现这一点。请帮助,我是R新手,我想学习这个强大的工具。

+0

什么是类变量 “TIME_” 的?你能否提供更多的数据点? – lizzie

回答

0

该链接中的答案(Compare time in R)具有很好的功能,您可以使用to.time使用chron包。这将有助于比较两次之间的差异。

这里有一个办法:

# create toy data 
set.seed(1) 
x <- data.frame(SERIAL_No = sample(5, 10, replace = TRUE), 
      Date = Sys.Date() - 1:10, 
      Time = format(Sys.time() - sample(1000, 10), "%H:%M")) 

# Define helper function from link above 
library(chron) 
to.times <- function(x) times(paste0(x, ":00")) 

# Change class of Time column to times 
x$Time <- to.times(x$Time) 

# Isolate observations past 00:00 (can switch to 5:00 when you use your data) 
x <- x[x$Time > to.times("00:00"), ] 

# Find observation closest to 00:00 for each serial number 
do.call(rbind, lapply(split(x, x$SERIAL_No), 
         function(a) a[which.min(a$Time - to.times("00:00")), ])) 
+0

It Works。非常感谢 – Van