[英]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.