如何查找 R 数据框中的列绝对距离?
绝对距离可以通过计算列值之间的差来找到。如果我们要距离为绝对距离,则需要使用 abs 函数。例如,假设我们有一个数据框 df,其中包含列 x 和 y,那么可以通过使用 dfAbsoluteDistance<−abs(dfy-df$x) 来查找绝对距离。
示例 1
考虑以下数据框
> set.seed(274) > x1<-rpois(20,5) > y1<-rpois(20,8) > df1<-data.frame(x1,y1) > df1
输出
x1 y1 1 6 11 2 1 4 3 4 2 4 7 12 5 4 5 6 6 10 7 6 14 8 6 8 9 2 11 10 3 8 11 3 8 12 2 6 13 1 6 14 2 10 15 4 4 16 6 11 17 4 10 18 9 3 19 3 1 20 9 8
创建具有绝对距离的新列
Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.
示例
> df1$Absolute_Distance<-abs(df1$y1-df1$x1) > df1
输出
x1 y1 Absolute_Distance 1 6 11 5 2 1 4 3 3 4 2 2 4 7 12 5 5 4 5 1 6 6 10 4 7 6 14 8 8 6 8 2 9 2 11 9 10 3 8 5 11 3 8 5 12 2 6 4 13 1 6 5 14 2 10 8 15 4 4 0 16 6 11 5 17 4 10 6 18 9 3 6 19 3 1 2 20 9 8 1
示例 2
> x2<-sample(0:9,20,replace=TRUE) > y2<-sample(1:10,20,replace=TRUE) > df2<-data.frame(x2,y2) > df2
输出
x2 y2 1 7 5 2 9 9 3 8 8 4 1 6 5 5 1 6 9 6 7 0 6 8 5 10 9 4 5 10 4 10 11 0 3 12 5 2 13 9 7 14 0 1 15 5 7 16 2 1 17 2 1 18 6 6 19 6 2 20 4 10
创建具有绝对距离的新列
示例
> df2$Distance<-abs(df2$y2-df2$x2) > df2
输出
x2 y2 Distance 1 7 5 2 2 9 9 0 3 8 8 0 4 1 6 5 5 5 1 4 6 9 6 3 7 0 6 6 8 5 10 5 9 4 5 1 10 4 10 6 11 0 3 3 12 5 2 3 13 9 7 2 14 0 1 1 15 5 7 2 16 2 1 1 17 2 1 1 18 6 6 0 19 6 2 4 20 4 10 6
广告