开发者

Writing functions in R - calling external functions from libraries

开发者 https://www.devze.com 2023-03-29 08:20 出处:网络
So I am trying to take a bit of code that I use for interactive selection and identification.It works outside of a function but gives an error when I try to run it as a stand alone function.

So I am trying to take a bit of code that I use for interactive selection and identification. It works outside of a function but gives an error when I try to run it as a stand alone function.

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)
  }

Basically it doesn't want to run the overlay function (function of the sp package). The error report is that I can't run the inherited functions??

Error in function (classes, fdef, mtable) : unable to find an inherited method for function "overlay", for signature "matrix", "SpatialPolygons"

Any ideas??? I'm new to function writing... so hopefully it will be easy.


This should work. overlay is deprecated and over should be used instead. The catch is that all objects should be 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)

Writing functions in R - calling external functions from libraries


You need to add a call to the package in your function:

 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

精彩评论

暂无评论...
验证码 换一张
取 消