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")]