我有一系列与一天中的时间相关的动物观察。我需要按照以下方式对它们进行分组以进行后续分析;与上一个相距不到10分钟的所有观察结果都属于同一组。如果观测值与上一个观测值相距十分钟以上,它将开始一个新的组。
为此,我使用if语句完成了一个for循环
wilde16 <- structure(list(Species = structure(c(1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = "wildebeest", class = "factor"),
Total_Ind = c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 1L, 1L,
1L, 1L, 1L, 1L, 1L), DateTime = structure(c(1464449354, 1464449370,
1464449393, 1464449402, 1464449876, 1464449954, 1464450303,
1464450624, 1464450640, 1464450656, 1464450953, 1464450969,
1464450985, 1464451132, 1464451148, 1464451165), class = c("POSIXct",
"POSIXt"), tzone = "Africa/Dar_es_Salaam")), row.names = c(99L,
100L, 101L, 102L, 103L, 104L, 105L, 106L, 107L, 110L, 128L, 129L,
132L, 142L, 144L, 146L), class = "data.frame")
class(wilde16$DateTime)
[1] "POSIXct" "POSIXt"
wilde16$DateTime[223]
[1] "2016-05-30 09:54:54 EAT"
z <- 0
for(i in 1:length(wilde16$DateTime)){
if(wilde16$DateTime[i+1]-wilde16$DateTime[i]<600){
wilde16$Group[i] <- z
}
else{
z <- z + 1
wilde16$Group[i] <- z
}
}
但是,当我运行它时,它会返回错误消息
“ if(wilde16 $ DateTime [i + 1]-wilde16 $ DateTime [i] <600)中的错误{ 缺少需要TRUE / FALSE的值”
即使我尝试尝试
i <- 1
(wilde16$DateTime[i + 1] - wilde16$DateTime[i] < 600)
它返回
[1] FALSE
怎么了?
答案 0 :(得分:1)
@Henry观察到,您遇到了索引问题。
如果试图在向量上查找间隔,则可以使用函数for
来避免findInterval()
循环。
interval <- seq.POSIXt(from = min(wilde16$DateTime), to = max(wilde16$DateTime), by = "10 min")
z <- findInterval(x = wilde16$DateTime, vec = interval)