【发布时间】:2015-09-10 20:32:48
【问题描述】:
我有一个值为 1:6 的向量,一个包含 15 分钟 bin 的数据帧和一个扫描数据的数据帧。数据框如下所示。
垃圾箱
idMin5Bin BinStart BinEnd
22 22 2015-08-13 10:15:00 2015-08-13 10:19:59
23 23 2015-08-13 10:20:00 2015-08-13 10:24:59
24 24 2015-08-13 10:25:00 2015-08-13 10:29:59
25 25 2015-08-13 10:30:00 2015-08-13 10:34:59
26 26 2015-08-13 10:35:00 2015-08-13 10:39:59
27 27 2015-08-13 10:40:00 2015-08-13 10:44:59
汽车
idTrip Link_IDLink StartCluster_id Speed firstScan
10 10 5 19 47.961 2015-08-13 10:11:49
11 11 5 14 118.800 2015-08-13 10:12:33
12 11 5 14 118.800 2015-08-13 10:13:16
13 12 5 22 47.793 2015-08-13 10:11:21
15 14 5 28 56.321 2015-08-13 10:13:09
24 22 5 52 45.692 2015-08-13 10:14:50
对于向量中的每个值,我想引用汽车表来查找具有与向量值匹配的LinkIDLink 值的所有汽车。
然后我想通过比较汽车 FirstScan 与 bins 表的 BinStart 和 BinEnd 表来对所有匹配项进行子集化。
最后,我想绘制子集中的值。
我能想到的唯一策略是使用嵌套循环(我知道这是不行的)。即使使用我的嵌套循环,我也会从下面的示例代码中得到以下错误。
for (i in 1:length(vector)){
tempcars<-cars[cars[,2]==i,]
for (k in 1:nrow(bins)){
tempcars1<-subset(tempcars, firstScan<bins[k,3] & firstScan>bins[k,2])
hist(tempcars1[,5], breaks =200)
}
}
Error in hist.default(unclass(x), unclass(breaks), plot = FALSE, warn.unused = FALSE, :
character(0) In addition: Warning messages:
1: In min(x) : no non-missing arguments to min; returning Inf
2: In max(x) : no non-missing arguments to max; returning -Inf
我当然想摆脱使用循环,但感谢任何有关循环的帮助。
【问题讨论】:
-
哦,firstScan是一次吗?您可能会在 tempcars1 中获得 NA,因为您要求 firstScan 在 BinStart 之前和 BinEnd 之后。
-
@ago 不,没有 NA。 firstScan 是一个日期戳。我已确保将所有日期值也转换为 POSIXct
-
呃,对不起,我想我把你的专栏弄糊涂了。
-
@ago,对不起,你是对的,我有 0 长度的 row.names 作为 tempcars1 的数据框
-
那么对于每一个
Link_IDLink,你想识别每辆车的binID??顺便说一句,data.table 包中的foverlaps(...)函数是最有效的方法。
标签: r