在R中编写函数 - 从库中调用外部函数
问题描述:
所以我试图拿一些我用于交互选择和识别的代码。它在函数之外工作,但是当我尝试将它作为独立函数运行时会发生错误。在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”
任何想法? ?我很新写作功能......所以希望这很容易。
答
您需要调用你的功能添加到包:
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'方法... –
答
这应该工作。 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)
请提供一个可重复的例子,并且在FWIW建议,而不是覆盖() – mdsumner
这工作正常,我 - 我不明白你报告,请更新问题的错误完整的细节。我认为这归结于你想要覆盖什么 - 是“数据”的意图是点,还是它可能是poylgons(或线)?如果不只是点你会想要包rgeos – mdsumner
库(rgdal); dsn mdsumner