我正在使用一个函数来识别一个序列,然后以分钟为单位计算序列的持续时间。当我在最后阶段将结果与数据 cbind 时,将返回持续时间,但返回的相邻列带有“NA”,而不是这些列中最初的值
d<-read.table(text='Date.Time Aerial
794 "2012-10-01 08:18:00" 1
795 "2012-10-01 08:34:00" 1
796 "2012-10-01 08:39:00" 1
797 "2012-10-01 08:42:00" 1
798 "2012-10-01 08:48:00" 1
799 "2012-10-01 08:54:00" 1
800 "2012-10-01 08:58:00" 1
801 "2012-10-01 09:04:00" 1
802 "2012-10-01 09:05:00" 1
803 "2012-10-01 09:11:00" 1
1576 "2012-10-01 09:17:00" 2
1577 "2012-10-01 09:18:00" 2
804 "2012-10-01 09:19:00" 1
805 "2012-10-01 09:20:00" 1
1580 "2012-10-01 09:21:00" 2
1581 "2012-10-01 09:23:00" 2
806 "2012-10-01 09:25:00" 1
807 "2012-10-01 09:32:00" 1
808 "2012-10-01 09:37:00" 1
809 "2012-10-01 09:43:00" 1', header=TRUE, stringsAsFactors=FALSE, row.names=1)
#Give correct data type
d$Aerial<- as.numeric(d$Aerial)
d$Date.Time<- as.POSIXct(d$Date.Time)
功能(识别天线 2 重复的序列和序列的持续时间):
fun1 <- function(data,aerial){
data_above <- 1L*(data$Aerial == aerial)
id_start <- paste(data$Date.Time[which(diff(c(0L,data_above))==1)])
id_end <- paste(data$Date.Time[which(diff(c(data_above,0L))== -1)])
res <- cbind(data[id_start,1:1],Duration=difftime(id_end,id_start, units='mins'))
return(res)
}
fun1(d,2)
回报:
Duration
[1,] NA 1
[2,] NA 2
持续时间是正确的,但是我希望它返回应该在相关列中的数据:
Date.Time Duration
[1,] 2012-10-01 09:11:00 1
[2,] 2012-10-01 09:21:00 2
我的实际 data.frame 有很多列而不仅仅是 Date.Time 并且它仍然为所有这些返回 NA