如何从数据框创建SpatialLinesDataFrame?


9

我已经在R中创建了一个data.frame。我想获得SpatialLinesDataFrame的结果,所以我理解我必须将data.frame转换为线,将线转换为SpatialLines,将SpatialLines转换为SpatialLinesDataFrame。我做了这个

filedata.frame=data.frame(matrix(file),ncol=14, byrow=T))
file=Lines(filedata.frame)

我得到了我想要的data.frame,但没有得到线。我确定这是基础知识,但是为什么我不能理解?


您的数据框看起来如何?坐标如何存储?你检查了?Lines吗?线需要两个参数作为输入Lines(slinelist, ID)
Iris

因此,每一行都有起点和终点。您是正确的行,我做到了:for(i在seq_along(lines)中){lines [[i]] <-Lines(list(Line(rbind(c(file $ x_f [i],file $ y_f [ I]),C(filedf $ x_tr [I],filedf $ y_tr [I])))),as.character(ⅰ))}
GFL

Answers:


11

这是sp小插图的扩展示例,演示了如何从普通的“ data.frame”对象创建“ SpatialLinesDataFrame”。我使用通过rgeosgLength从单个“ SpatialLines”的长度创建的一些示例数据。请注意,传递到的创建的数据集的必须与先前定义的行ID(在这种情况下为“ a”和“ b”)相同。rownamesSpatialLinesDataFrame

library(sp)

## from the sp vignette:
l1 <- cbind(c(1, 2, 3), c(3, 2, 2))
l2 <- cbind(c(1, 2, 3), c(1, 1.5, 1))

Sl1 <- Line(l1)
Sl2 <- Line(l2)

S1 <- Lines(list(Sl1), ID = "a")
S2 <- Lines(list(Sl2), ID = "b")

Sl <- SpatialLines(list(S1, S2))

## sample data: line lengths
library(rgeos)
df <- data.frame(len = sapply(1:length(Sl), function(i) gLength(Sl[i, ])))
rownames(df) <- sapply(1:length(Sl), function(i) Sl@lines[[i]]@ID)


## SpatialLines to SpatialLinesDataFrame
Sldf <- SpatialLinesDataFrame(Sl, data = df)

plot(Sldf, col = c("red", "blue"))
text(labels = paste0("length = ", round(Sldf@data$len, 2)), 
     x = gCentroid(Sldf, byid = TRUE)$x,
     y = gCentroid(Sldf, byid = TRUE)$y)

在此处输入图片说明

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.