3D欧氏距离识别未知样本
3D euclidean distance to identify unknown samples
我有一个名为 mydf
的数据框,其中我有三个主要协变量(PCA.1、PCA.2、PCA.3)。我想获得 3d 距离矩阵并获得所有比较 Samples
之间的最短欧氏距离。在另一个名为 myref
的数据框中,我有一些已知的 Samples
和一些 unknown
样本。通过计算mydf的最短欧几里德距离,我想将已知的Identity
分配给未知的样本。有人可以帮我完成这件事吗?
mydf
mydf <- structure(list(Sample = c("1", "2", "4", "5", "6", "7", "8",
"9", "10", "12"), PCA.1 = c(0.00338, -0.020373, -0.019842, -0.019161,
-0.019594, -0.019728, -0.020356, 0.043339, -0.017559, -0.020657
), PCA.2 = c(0.00047, -0.010116, -0.011532, -0.011582, -0.013245,
-0.011751, -0.010299, -0.005801, -0.01, -0.011334), PCA.3 = c(-0.008787,
0.001412, 0.003751, 0.00371, 0.004242, 0.003738, 0.000592, -0.037229,
0.004307, 0.00339)), .Names = c("Sample", "PCA.1", "PCA.2", "PCA.3"
), row.names = c(NA, 10L), class = "data.frame")
我的参考
myref<- structure(list(Sample = c("1", "2", "4", "5", "6", "7", "8",
"9", "10", "12"), Identity = c("apple", "unknown", "ball", "unknown",
"unknown", "car", "unknown", "cat", "unknown", "dog")), .Names = c("Sample",
"Identity"), row.names = c(NA, 10L), class = "data.frame")
uIX = which(myref$Identity == "unknown")
dMat = as.matrix(dist(mydf[, -1])) # Calculate the Euclidean distance matrix
nn = apply(dMat, 1, order)[2, ] # For each row of dMat order the values increasing values.
# Select nearest neighbor (it is 2, because 1st row will be self)
myref$Identity[uIX] = myref$Identity[nn[uIX]]
注意上面的代码会将一些身份设置为unknown
。相反,如果您想匹配具有已知身份的最近邻居,请将第二行更改为
dMat[uIX, uIX] = Inf
我有一个名为 mydf
的数据框,其中我有三个主要协变量(PCA.1、PCA.2、PCA.3)。我想获得 3d 距离矩阵并获得所有比较 Samples
之间的最短欧氏距离。在另一个名为 myref
的数据框中,我有一些已知的 Samples
和一些 unknown
样本。通过计算mydf的最短欧几里德距离,我想将已知的Identity
分配给未知的样本。有人可以帮我完成这件事吗?
mydf
mydf <- structure(list(Sample = c("1", "2", "4", "5", "6", "7", "8",
"9", "10", "12"), PCA.1 = c(0.00338, -0.020373, -0.019842, -0.019161,
-0.019594, -0.019728, -0.020356, 0.043339, -0.017559, -0.020657
), PCA.2 = c(0.00047, -0.010116, -0.011532, -0.011582, -0.013245,
-0.011751, -0.010299, -0.005801, -0.01, -0.011334), PCA.3 = c(-0.008787,
0.001412, 0.003751, 0.00371, 0.004242, 0.003738, 0.000592, -0.037229,
0.004307, 0.00339)), .Names = c("Sample", "PCA.1", "PCA.2", "PCA.3"
), row.names = c(NA, 10L), class = "data.frame")
我的参考
myref<- structure(list(Sample = c("1", "2", "4", "5", "6", "7", "8",
"9", "10", "12"), Identity = c("apple", "unknown", "ball", "unknown",
"unknown", "car", "unknown", "cat", "unknown", "dog")), .Names = c("Sample",
"Identity"), row.names = c(NA, 10L), class = "data.frame")
uIX = which(myref$Identity == "unknown")
dMat = as.matrix(dist(mydf[, -1])) # Calculate the Euclidean distance matrix
nn = apply(dMat, 1, order)[2, ] # For each row of dMat order the values increasing values.
# Select nearest neighbor (it is 2, because 1st row will be self)
myref$Identity[uIX] = myref$Identity[nn[uIX]]
注意上面的代码会将一些身份设置为unknown
。相反,如果您想匹配具有已知身份的最近邻居,请将第二行更改为
dMat[uIX, uIX] = Inf