2015-09-14 98 views
5

总结:我清理鱼遥测数据集(即,通过时间空间坐标)使用data.table包在R(版本)(1.9.5版本)在Windows 7电脑上。一些数据点是错误的(例如,遥测设备回波)。我们可以说这些观点是错误的,因为鱼的移动距离远远超过生物学可能并且脱颖而出。实际数据集包含来自30条鱼的超过2,000,000行数据,因此使用data.table包。计算两个行之间的距离在问题data.table

我删除的距离太远(即行进距离大于最大距离)的点。但是,我需要重新计算删除点后移动的点之间的距离,因为有时会在群中错误地记录2-3个数据点。目前,我有一个可以完成工作的for循环,但可能远没有达到最佳效果,而且我知道我可能会缺少data.table软件包中的一些强大工具。

作为技术说明,我的空间尺度足够小,以至于欧几里得距离可以工作,并且我的最大距离标准是生物学合理的。

我在哪里寻找帮助:我查看过所以发现了几个有用的答案,但没有一个完全符合我的问题。具体而言,所有其他答案仅将一列数据与行之间进行比较。

  1. answer比较了使用data.table两行,但只能看一个变量。

  2. answer看起来很有前途,并使用Reduce,但我不知道如何使用Reduce两栏。

  3. answer使用从data.table索引功能,但我不知道如何使用它与距离函数。

  4. 最后,这个answer演示data.tableroll函数。但是,我无法弄清楚如何在这个函数中使用两个变量。

这里是我的MVCE:

library(data.table) 
## Create dummy data.table 
dt <- data.table(fish = 1, 
       time = 1:6, 
       easting = c(1, 2, 10, 11, 3, 4), 
       northing = c(1, 2, 10, 11, 3, 4)) 
dt[ , dist := 0] 

maxDist = 5 

## First pass of calculating distances 
for(index in 2:dim(dt)[1]){ 
    dt[ index, 
     dist := as.numeric(dist(dt[c(index -1, index), 
       list(easting, northing)]))] 
} 

## Loop through and remove points until all of the outliers have been 
## removed for the data.table. 
while(all(dt[ , dist < maxDist]) == FALSE){ 
    dt <- copy(dt[ - dt[ , min(which(dist > maxDist))], ]) 
    ## Loops through and recalculates distance after removing outlier 
    for(index in 2:dim(dt)[1]){ 
     dt[ index, 
      dist := as.numeric(dist(dt[c(index -1, index), 
        list(easting, northing)]))] 
    } 
} 

回答

4

我有点困惑,为什么你把重新计算的距离(和不必要的复制数据),而不是仅仅做一个合格:

last = 1 
idx = rep(0, nrow(dt)) 
for (curr in 1:nrow(dt)) { 
    if (dist(dt[c(curr, last), .(easting, northing)]) <= maxDist) { 
    idx[curr] = curr 
    last = curr 
    } 
} 

dt[idx] 
# fish time easting northing 
#1: 1 1  1  1 
#2: 1 2  2  2 
#3: 1 5  3  3 
#4: 1 6  4  4 
+0

我正在传递两次数据并复制,因为我找不到一个单一的解决方案:)。谢谢您的回答! –

+1

哈哈,很高兴帮助 – eddi

相关问题