【发布时间】:2017-06-30 17:36:00
【问题描述】:
我在 r 中有以下数据框
count1 count2 count3
0 12 11
12 13 44
22 32 13
我想计算count2,count1和count3和count2之间的距离,如下所示
sqrt(abs(count2-count1) + abs(count3-count2))
到数据帧的每一行。我想要的数据框如下
count1 count2 count3 distance
0 12 11 sqrt(abs(12-0)+abs(12-11))
12 13 44 sqrt(abs(13-12)+abs(44-13))
22 32 13 sqrt(abs(32-22)+abs(13-32))
我的做法是使用 for 循环
for(i in 1:nrow(df)){
df$distance[i] <- sqrt(abs(df$count1[i] - df$count2[i]) + abs(df$count2[i] - df$count3[i]))
}
上面有没有更好的方法?
【问题讨论】:
-
您不需要 for 循环,因为此操作在 R 中是矢量化的。通过删除大约 15 个字符来修改您的内部行的简单单行符就可以了:
df$distance <- sqrt(abs(df$count1 - df$count2) + abs(df$count2 - df$count3))。 akrun 的回答使这使用with变得更简单。根本不需要任何包。
标签: r