在R中编写函数 - 从库中调用外部函数

时间:2011-08-19 01:46:21

标签: function r inherited

所以我想尝试一些用于交互式选择和识别的代码。它在函数之外工作,但在我尝试将其作为独立函数运行时会出错。

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 包的功能)。错误报告是我无法运行继承的函数??

  

函数错误(classes,fdef,mtable):无法找到   函数“overlay”的继承方法,用于签名“matrix”,   “SpatialPolygons”

任何想法???我是函数写作的新手...所以希望它很容易。

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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)
 }