【发布时间】:2015-04-11 04:36:22
【问题描述】:
我已经阅读了矢量化作为加速 for 循环的解决方案。但是,我在 for 循环中创建的数据结构似乎需要是 data.frame/table。
这是场景:
我有一个包含序列号和时间戳的大表。多个时间戳可以应用于同一个序列号。我只想要每个序列号的最新时间戳。
我现在的方法是创建一个具有唯一序列号的向量。然后对于通过这个向量的每个循环,我创建一个临时表,其中包含序列号/时间戳组合('temp')的所有观察结果。然后我取出这个临时表的最后一个条目(使用 tail 命令)并将其放入另一个表中,该表最终将保存所有唯一序列号及其最新时间戳('last.pass')。最后,我只是从起始表序列中删除无法找到数字/时间戳组合'last.pass'的行
这是我的代码:
#create list of unique serial numbers found in merged 9000 table
hddsn.unique <- unique(merge.data$HDDSN)
#create empty data.table to populate
last.pass < data.table(HDDSN=as.character(1:length(hddsn.unique)),
ENDDATE=as.character(1:length(hddsn.unique)))
#populate last.pass with the combination of serial numbers and their latest timestamps
for (i in 1:length(hddsn.unique)) {
#create temporary table that finds all serial number/timestamp combinations
temp <- merge.data[merge.data$HDDSN %in% hddsn.unique[i],][,.(HDDSN, ENDDATE)]
#populate last.pass with the latest timestamp record for every serial number
last.pass[i,] <- tail(temp, n=1)
}
match <- which(merge.data[,(merge.data$HDDSN %in% last.pass$HDDSN) &
(merge.data$ENDDATE %in% last.pass$ENDDATE)]==TRUE)
final <- merge.data[match]
我的终极问题是,我如何保持这个脚本的自动化特性,同时加快它的速度,比如通过矢量化或将它变成一个函数。
谢谢!!!
【问题讨论】:
-
您应该包含示例输入数据和该示例数据的所需输出,以解决您的问题reproducible
-
根据您的描述,这听起来很简单,无论是使用 dplyr 还是数据表,甚至是基本功能。但是,正如弗里克先生所说,我们需要一个例子。只需 5-10 行输入和您想要的输出。使用
dput()分享您的数据,我们将获得所有的写入类。 -
另外,当你说“大”时,最好有一个规模。你的意思是> 1000万行? 1-1000万?一个数量级的估计就足够了。
-
@Martin Morgan 说得对。这就是数据的样子。大小接近 100 万行。我正在尝试他的方法,并会回复您。
标签: r performance for-loop automation vectorization