对R中的数据帧进行矢量化循环

时间:2013-02-08 00:34:35

标签: r coding-style

我有一个包含三列的数据框:ref,target,distance。每个ref都有一个到同一组目标的测量距离,我想得到每个ref的最小距离矢量。现在我用for循环做这个,但似乎应该有一种方法来矢量化它。

这是我的代码:

refs <- levels(data$ref)

result <- c()
for (ref in refs) {
    # Find the minimum distance for observations with the current ref
    # but be sure to protect against ref == target!
    best_dist <- min(data[data$ref == ref & data$target != ref,]$distance)
    result <- c(result, best_dist)
}

我注定要通过这种方式设置数据框还是有一种很好的方法来对此进行矢量化?谢谢你的帮助!

1 个答案:

答案 0 :(得分:6)

永远不要使用ccbindrbind在循环中增长对象。每次都会复制该对象。 而是预先分配到正确的大小(或者如果结果是流动的话,则会高估一些)。

话虽如此,这里不需要循环

我喜欢data.table的内存效率和编码优雅。

 library(data.table)
 DT <- data.table(data)


 DT[ref != target, list(bestdist = min(distance)), by = ref] 

如果ref和target是具有不同级别的因子列(如注释中所示),则要么使它们具有相同的级别,要么转换为字符

 DT[as.character(ref) != as.character(target),  list(bestdist = min(distance)), by = ref] 
相关问题