2016-08-01 94 views
0

兩個現有的表的一個非常小的樣品在Spotfire存在:在Spotfire上使用R,如何通過在查找表中搜索最接近的值來檢索值?

主表

Road Easting Northing 
M1 456252 278173 
M1 443281 389200 
M1 447205 335640 
M1 500425 233986 

查找表

CP  Easting Northing 
8219 448325 388413 
36004 457081 275396 
81549 500244 234300 
56005 447134 336976 
73366 446865 330080 
73039 505000 223710 

目標

這將是一個新的列中的結果指向最近的CP。

Road Easting Northing CP 
M1 456252 278173 36004 
M1 443281 389200 8219 
M1 447205 335640 56005 
M1 500425 233986 81549 

是否有公式或R scriopt能夠返回此查找列?

我基本上試圖在第二個表中的第一個表中搜索Eastings和Northings的最近值。然後通過選擇最近的北部和東部查找CP(這是唯一的ID)。

有沒有人有任何想法如何做到這一點?

+0

如果這是完全匹配,那麼您正在尋找'merge'。類似'merge(df1,df2,by = c(「Easting」,「Northing」))' – lmo

+0

是否要特別使用R?我只問,因爲在spotfire中,這很容易實現,沒有R – scsimon

+0

scsimon - 我只是希望能夠匹配它們,所以如果可以在不使用R的情況下完成,那將非常棒! – kc8g15

回答

0

這段代碼能工作嗎?

whichindex <- data.frame(
        (sapply(main$Easting, function(x) which.min(abs(x - lookup$Easting)))), 
        (sapply(main$Northing, function(y) which.min(abs(y - lookup$Northing)))) 
       ) 
output <- cbind(main,whichindex)