R函数来计算坐标
R function to count coordinates
尝试通过 mapply 或类似的方法在不进行迭代的情况下完成它 - 我在 R 中有一个空间数据框,我想对所有更复杂的形状进行子集化 - 即具有 10 个或更多坐标的形状。 shapefile 很大(10k 形状),适用于小样本的方法对于大样本来说非常慢。迭代法为
Street$cc <-0
i <- 1
while(i <= nrow(Street)){
Street$cc[i] <-length(coordinates(Street)[[i]][[1]])/2
i<-i+1
}
我怎样才能以任何阵列方式获得相同的效果?我在从顶部向下访问几个级别时遇到问题 (Shapefile/lines/Lines/coords)
我试过了:
Street$cc <- lapply(slot(Street, "lines"),
function(x) lapply(slot(x, "Lines"),
function(y) length(slot(y, "coords"))/2))
/除以2因为每个坐标都是一对2值/
但仍然是 returns 一个列表,其中包含每行的项目数,而不是告诉我有多少项目的整数。如何获取空间数据框中每个形状的坐标数?抱歉,我没有可重现的示例,但您可以检查任何空间文件 - 它更多的是关于访问低级别 属性 而不是一个非常具体的问题。
编辑:
我解决了这个问题 - 使用函数
tail()
这是一个可重现的例子。和你的略有不同,因为你没有提供数据,但是原理是一样的。下钻复杂S4结构时的'principle'是注意每一层是list还是slot,访问list用[[]]
,slot用@
[=15] =]
首先让我们得到一个空间多边形。我将使用美国各州边界;
library(maps)
local.map = map(database = "state", fill = TRUE, plot = FALSE)
IDs = sapply(strsplit(local.map$names, ":"), function(x) x[1])
states = map2SpatialPolygons(map = local.map, ID = IDs)
现在我们可以像这样对少于 200 个顶点的多边形进行子集化:
# Note: next line assumes that only interested in one Polygon per top level polygon.
# I.e. assumes that we have only single part polygons
# If you need to extend this to work with multipart polygons, it will be
# necessary to also loop over values of lower level Polygons
lengths = sapply(1:length(states), function(i)
NROW(states@polygons[[i]]@Polygons[[1]]@coords))
simple.states = states[which(lengths < 200)]
plot(simple.states)
尝试通过 mapply 或类似的方法在不进行迭代的情况下完成它 - 我在 R 中有一个空间数据框,我想对所有更复杂的形状进行子集化 - 即具有 10 个或更多坐标的形状。 shapefile 很大(10k 形状),适用于小样本的方法对于大样本来说非常慢。迭代法为
Street$cc <-0
i <- 1
while(i <= nrow(Street)){
Street$cc[i] <-length(coordinates(Street)[[i]][[1]])/2
i<-i+1
}
我怎样才能以任何阵列方式获得相同的效果?我在从顶部向下访问几个级别时遇到问题 (Shapefile/lines/Lines/coords)
我试过了:
Street$cc <- lapply(slot(Street, "lines"),
function(x) lapply(slot(x, "Lines"),
function(y) length(slot(y, "coords"))/2))
/除以2因为每个坐标都是一对2值/ 但仍然是 returns 一个列表,其中包含每行的项目数,而不是告诉我有多少项目的整数。如何获取空间数据框中每个形状的坐标数?抱歉,我没有可重现的示例,但您可以检查任何空间文件 - 它更多的是关于访问低级别 属性 而不是一个非常具体的问题。
编辑: 我解决了这个问题 - 使用函数
tail()
这是一个可重现的例子。和你的略有不同,因为你没有提供数据,但是原理是一样的。下钻复杂S4结构时的'principle'是注意每一层是list还是slot,访问list用[[]]
,slot用@
[=15] =]
首先让我们得到一个空间多边形。我将使用美国各州边界;
library(maps)
local.map = map(database = "state", fill = TRUE, plot = FALSE)
IDs = sapply(strsplit(local.map$names, ":"), function(x) x[1])
states = map2SpatialPolygons(map = local.map, ID = IDs)
现在我们可以像这样对少于 200 个顶点的多边形进行子集化:
# Note: next line assumes that only interested in one Polygon per top level polygon.
# I.e. assumes that we have only single part polygons
# If you need to extend this to work with multipart polygons, it will be
# necessary to also loop over values of lower level Polygons
lengths = sapply(1:length(states), function(i)
NROW(states@polygons[[i]]@Polygons[[1]]@coords))
simple.states = states[which(lengths < 200)]
plot(simple.states)