[英]Is there a way in R to create a matrix of nearest neighbours and variable values inR?
我有看起来像这样的数据:
identity growth x-pos y-pos
1: Z 0.1 0.5 0.7
2: B 0.1 0.1 0.0
3: C 0.2 4.6 2.5
4: D 0.3 5.6 5.0
5: A 0.4 0.2 1.0
6: P 0.1 0.4 2.0
我想比较每个具有唯一标识的对象的 n 个最近邻居之间的增长值是否相关。 因此,基本上创建一个矩阵,该矩阵根据x-pos
和y-pos
表示的位置为每个唯一identity
行标识 5 个最近的邻居,并在对象的growth
值(例如Z
)和第一个的增长值之间进行关联, Z
第 2、第 3、第 4 和第 5 个最近邻。
我尝试制作欧几里得矩阵,然后使用 ADE 包使用自相关度量,但想知道是否有更简单的方法来构建这样的矩阵。
之间执行corelations
growth
对象的值(例如Z
)和第一,第二,第三,第四的生长值和第五最近邻Z
您无法计算两点之间的相关性。
我能想到的最相似的事情是计算您的点与其平均邻居之间的相关性,或者进行成对测试来比较它们。 但这将适用于所有“对象”,而不是每个对象的相关性(因为每个对象只有 1 个点)。
创建一个矩阵,根据 x-pos 和 y-pos 表示的位置为每个唯一标识行标识 5 个最近的邻居
# read in data
df <- tribble(
~identity, ~growth, ~`x-pos`, ~`y-pos`,
"Z", 0.1, 0.5, 0.7,
"B", 0.1, 0.1, 0.0,
"C", 0.2, 4.6, 2.5,
"D", 0.3, 5.6, 5.0,
"A", 0.4, 0.2, 1.0,
"P", 0.1, 0.4, 2.0)
# here with 3 neighbors since we have only 6 points
n_neighbors <- 3
# make matrix of coordinates
mat <- as.matrix(df[,3:4])
rownames(mat) <- df$identity
# compute [euclidian] distances
dmat <- as.matrix(dist(mat))
# find neighbors (by name)
nei_mat <- apply(dmat, 1,
function(crow) {names(sort(crow))[seq_len(n_neighbors+1)]})[-1,]
# match names to initial data frame to make matrix of growth
ref_growth_mat <- matrix(df$growth, dimnames=list(df$identity))
growth_mat <- matrix(ref_growth_mat[nei_mat,], nrow = n_neighbors)
colnames(growth_mat) <- df$identity
# done
growth_mat
#> Z B C D A P
#> [1,] 0.4 0.1 0.3 0.2 0.1 0.4
#> [2,] 0.1 0.4 0.1 0.1 0.1 0.1
#> [3,] 0.1 0.1 0.1 0.1 0.1 0.1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.