Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/79.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R函数计算相距一定距离的所有索引对_R - Fatal编程技术网

R函数计算相距一定距离的所有索引对

R函数计算相距一定距离的所有索引对,r,R,给定一个带有数字列的数据帧,有什么快速方法可以确定索引对矩阵,从而使相关数字的绝对距离等于某个固定值 例如: index x 1 5 2 7 3 8 4 9 5 9.5 输出应该是 index1 index2 2 3 3 4 如果固定距离为1,并且 index1 index2 1 2 如果固定距离为2。一个选项是sqldf,根据x列中的差异将df合并到自身中: library(sqldf) res <-

给定一个带有数字列的数据帧,有什么快速方法可以确定索引对矩阵,从而使相关数字的绝对距离等于某个固定值

例如:

index x
  1   5
  2   7
  3   8
  4   9
  5   9.5
输出应该是

index1 index2
   2     3
   3     4
如果固定距离为1,并且

index1 index2
  1      2

如果固定距离为2。

一个选项是
sqldf
,根据
x
列中的差异将
df
合并到自身中:

library(sqldf)
res <- sqldf("SELECT l.`index` as index1, r.`index` as index2
              FROM df        as l
              INNER JOIN df  as r
              ON r.x - l.x = 1")

res
#  index1 index2
#1      2      3
#2      3      4
库(sqldf)

res如果固定距离为2,是否还应存在
index=2/index=4
对?x的值是否按照示例中的顺序排序?
dist_mat  <- as.matrix(dist(df[,2]))
dist_mat2 <- dist_mat*lower.tri(dist_mat)
res <- data.frame(index1=rep(row.names(dist_mat2),ncol(dist_mat2)),
                 index2=rep(colnames(dist_mat2),each=nrow(dist_mat2)),
                 x=c(dist_mat2))

res[res$x== 1, c("index1","index2")]