1

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

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):无法找到函数“overlay”、签名“matrix”、“SpatialPolygons”的继承方法

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

4

2 回答 2

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)

在此处输入图像描述

于 2011-12-05T15:37:07.827 回答
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)
 } 
于 2011-12-05T15:22:32.577 回答