簡體   English   中英

根據2個數值向量(坐標)中的緊密匹配值分配因子水平

[英]assign a factor level based on closely matching values in 2 numerical vectors (coordinates)

我在數據幀中有一個參考坐標列表,該坐標在2d曲面上定位了菌落:

colonies <- c("a", "b", "c", "d")
x_ref <- c(1206, 870, 1932, 57)
y_ref <- c(6631, 157, 6510, 329)

ref.df <- cbind(colonies, x_ref, y_ref)

我有一個第二個數據幀,其中包含對2d曲面的連續觀察:觀察到的菌落有x和y坐標,我需要將菌落名稱分配給此df的正確行。 但是坐標可能會稍微偏一點,所以我需要內置一個公差值,並且會對同一菌落進行多次觀察。

因此,如果存在x == 1226和y == 6652的行,我希望將該行標記為“ a”,而隨后的x == 1197和y == 6593的行也被分配為“ a”,而x == 1208和y == 3451的行將被分配為NA,因為它與參考數據幀中的任何菌落都不緊密匹配。 理想情況下,我希望能夠控制“公差”值。

RI中的所有功能都發現搜索不允許在觀察到的坐標中存在輕微誤差(例如,&in%不允許)。 我可以看到如何使用for循環以及if / else將一個值與向量+/-錯誤中的所有值進行比較,而不是值的向量中的x和y進行比較。

抱歉,很長的帖子。

================================================== ======================

我認為最好的辦法是自己計算距離。

#First, a data.frames is better than a matrix for mixed types
ref.df <- data.frame(colonies, x_ref, y_ref)

#new data to classify
new.df<-data.frame(
  x = c(1226,1197,1208),
  y = c(6652,6593,3451)
)

#calculate pairwise distances
mydist<-as.matrix(
    dist(rbind(setNames(ref.df[,2:3], c("x","y")), 
    new.df[,1:2])))
    [-(1:nrow(ref.df)), 1:nrow(ref.df)]

#apply threshold
is.na(mydist) <- mydist>500
#define helper function to classify each match
which.max.na <- function(x) if (all(is.na(x))) NA else which.min(x)
#assign new categries
newdf$colonies <- ref.df$colonies[apply(mydist,1, which.max.na)]

當我們只對子集真正感興趣時,因為dist()所有成對比較,所以這可能效率不高。 但這完全取決於您的數據量。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM