2011-08-19 54 views
1

所以我試圖拿一些我用於交互選擇和識別的代碼。它在函數之外工作,但是當我嘗試將它作爲獨立函數運行時會發生錯誤。在R中編寫函數 - 從庫中調用外部函數

my.identify <- function(data) 
    { 
    # allows you to create a polygon by clicking on map 
    region = locator(type = "o") 
    n = length(region$x) 
    p = Polygon(cbind(region$x, region$y)[c(1:n,1),]) 
    ps = Polygons(list(p), ID="region") 
    sps = SpatialPolygons(list(ps)) 

    # returns all data that overlaps new polygon sps 
    a=data[!is.na(overlay(data,sps)),] # here is the problem 
    return(a) 
    } 

基本上它不希望運行的疊加功能(SP包的功能)。錯誤報告是我無法運行繼承的功能?

錯誤的功能(類,FDEF,mtable):無法找到函數 「覆蓋」 的 繼承的方法,對於簽名 「矩陣」, 「SpatialPolygons」

任何想法? ?我很新寫作功能......所以希望這很容易。

+1

請提供一個可重複的例子,並且在FWIW建議,而不是覆蓋() – mdsumner

+0

這工作正常,我 - 我不明白你報告,請更新問題的錯誤完整的細節。我認爲這歸結於你想要覆蓋什麼 - 是「數據」的意圖是點,還是它可能是poylgons(或線)?如果不只是點你會想要包rgeos – mdsumner

+0

庫(rgdal); dsn < - system.file(「vectors」,package =「rgdal」)[1];城市< - readOGR(dsn = dsn,layer =「cities」);圖(市); my.identify(市); 。 。 。工作正常,但你需要處理錯誤處理的細節以及不可思議的覆蓋 – mdsumner

回答

0

您需要調用你的功能添加到包:

my.identify <- function(data) 
{ 
     require('sp') ## Call to load the sp package for use in stand alone function 
     # allows you to create a polygon by clicking on map 
     region = locator(type = "o") 
     n = length(region$x) 
     p = Polygon(cbind(region$x, region$y)[c(1:n,1),]) 
     ps = Polygons(list(p), ID="region") 
     sps = SpatialPolygons(list(ps)) 


     # returns all data that overlaps new polygon sps 
     a=data[!is.na(overlay(data,sps)),] 

     return(a) 
} 
+0

如果'sp'沒有加載,你認爲它會一路覆蓋嗎? 'Polygon','Polygons'和'SpatialPolygons'都是'sp'方法... –

1

這應該工作。 overlay已被棄用,應該使用over。問題是所有對象都應該是Spatial*。 ?

xy <- data.frame(x = runif(40, min = -200, max = 200), 
    y = runif(40, min = -200, max = 200)) 
plot(xy) 
my.identify <- function(data) { 
    # allows you to create a polygon by clicking on map 
    region = locator(type = "o") 
    n = length(region$x) 
    p = Polygon(cbind(region$x, region$y)[c(1:n,1),]) 
    ps = Polygons(list(p), ID="region") 
    sps = SpatialPolygons(list(ps)) 

    # returns all data that overlaps new polygon sps 
    a=data[!is.na(over(SpatialPoints(data),sps)),] 
    return(a) 
} 
ident <- my.identify(xy) 
points(ident, pch = 16) 

enter image description here