如何创建 SpatialLine 对象

How to create SpatialLine object

我正在使用 sp 包创建 SpatialLines 对象并将其保存在对象列表 allLines 中。稍后我需要将 SpatialLines 相互比较,但这超出了当前的问题。

到目前为止我只需要构造SpatialLines个对象。这是基于 hrbrmstr 答案的最后一个代码:

library(sp)
allLines <- NULL
x <- c(1,5,4,8)
y <- c(1,3,4,7)
xy <- cbind(x,y)
xy.sp = sp::SpatialPoints(xy)
spl <- SpatialLines(list(Lines(Line(xy.sp), ID="a")))
allLines <- rbind(allLines,spl)

错误信息:

Error in (function (classes, fdef, mtable) : unable to find an inherited method for function ‘proj4string’ for signature ‘"NULL"’

如何解决这个问题?

是:

library(sp)

x <- c(1,5,4,8)
y <- c(1,3,4,7)
SpatialLines(list(Lines(Line(cbind(x,y)), ID="a")))

## An object of class "SpatialLines"
## Slot "lines":
## [[1]]
## An object of class "Lines"
## Slot "Lines":
## [[1]]
## An object of class "Line"
## Slot "coords":
##      x y
## [1,] 1 1
## [2,] 5 3
## [3,] 4 4
## [4,] 8 7
## 
## 
## 
## Slot "ID":
## [1] "a"
## 
## 
## 
## Slot "bbox":
##   min max
## x   1   8
## y   1   7
## 
## Slot "proj4string":
## CRS arguments: NA

你在找什么?

回到你的最后一个问题,试试

library(sp)
as(xy.spdf, "SpatialLines")

或者,要创建一个 Lines 对象(这可能不是您想要的),

as(xy.spdf, "SpatialLines")@lines[[1]]

如果你来到这个问题是为了了解如何制作一组 (正如函数名称所暗示的那样,SpatialLines)你可以找到sp 库中的示例,在 "SpatialLines-class".

下归档

我发现他们的示例有点奇怪,所以我对其进行了编辑,以便更了解我通常如何查看数据。

## Make some line segments from points 
## Note, l1a and l1b are a group of two lines
l1a <- rbind(c(1, 3), c(2,2) ,c(3,2))
l1b <- l1a + .05
l2 <- rbind(c(1,1), c(2,1.5), c(3,1))

## At this point it's just a matrix, and you can plot the points
plot(l1a, type="l", xlim=c(1,3.25), ylim=c(2,3.25), xlab="", ylab="")
lines(l1b)

## Make convert the matrix objects to line objects
Sl1a <- Line(l1a)
Sl1b <- Line(l1b)
Sl2 <- Line(l2)

## Group the individual lines into "lines"
S1 <- Lines(list(Sl1a, Sl1b), ID="a")
S2 <- Lines(list(Sl2), ID="b")

## Now combine the line groups into a "spatial line object"
Sl <- SpatialLines(list(S1,S2))

## Plot the group, then (for illustration) add each line 
## separately with color to illustrate the groups
plot(Sl)
plot(SpatialLines(list(S1)), add=T, col="red")
plot(SpatialLines(list(S2)), add=T, col="blue")

## Examine the properties
summary(Sl)
plot(Sl, col = c("red", "blue"))

两个空间线图如下所示:

请注意,矩阵对象在示例中已命名行。我看不出这样做有什么好处,而且它令人困惑,因为名称重叠但与给定的 ID 不对应。