R - 将两组坐标转换为空间点数据帧

时间:2016-09-21 05:02:05

标签: r gis

我有2组坐标和其他变量的数据。

如何将两组坐标转换为SpatialPoint数据框?

From     To      Dist        xFrom    yFrom      xTo       yTo
BARINGO BOMET   1.7019462   35.9659 0.819193    35.3146  -0.753203
BARINGO BONDO   1.9648836   35.9659 0.819193    34.2529  -0.143303
BARINGO BUNGOMA 1.3139522   35.9659 0.819193    34.6606   0.668653

我有两组坐标(xFrom,yFrom)和(xTo,yTo),并尝试了以下不起作用的代码

library(sp)

df <- sample[-4:-7]
xy1 <- sample[4:5]
xy2 <- sample[6:7]

SPDF <- SpatialPointsDataFrame(coords=xy1, coords=xy2, data=df)

1 个答案:

答案 0 :(得分:0)

我提前道歉,误解了你的问题并做了错误的编辑 coords应该是一个matrixdata.framenrow(data)应该等于点数。

xy1.1 <- as.matrix(xy1)
xy2.1 <- as.matrix(xy2)   # rbind(xy1, xy2) doesn't run because of difference colnames.
xy12 <- rbind(xy1.1, xy2.1)
df2 <- rbind(df, df)

SPDF <- SpatialPointsDataFrame(coords = xy12, data = df2)
[编辑]

您可以使用SpatialPointsDataFrame过滤data.frame数据。

df1 <- data.frame(df, Attribute = rep("from", nrow(df)), ID = 1:nrow(df))
df2 <- data.frame(df, Attribute = rep("to", nrow(df)), ID = 1:nrow(df))
xy12 <- rbind(as.matrix(xy1), as.matrix(xy2))
df12 <- rbind(df1, df2)

SPDF <- SpatialPointsDataFrame(xy12, data = df12)
# sort.list <- order(SPDF@data$ID)
# sorted.SPDF <- SPDF[sort.list,]

head(SPDF, n=4)
#            coordinates    From      To     Dist Attribute ID
# 1  (35.9659, 0.819193) BARINGO   BOMET 1.701946      from  1
# 2  (35.9659, 0.819193) BARINGO   BONDO 1.964884      from  2
# 3  (35.9659, 0.819193) BARINGO BUNGOMA 1.313952      from  3
# 4 (35.3146, -0.753203) BARINGO   BOMET 1.701946        to  1

SPDF[SPDF@data$Attribute == "from",]  # only "from"
SPDF[SPDF@data$Attribute == "to",]    # only "to"
# ind1 <- which(SPDF@data$Attribute == "from")

plot(SPDF, col="#00000000")           # a draft to set coordinates
plot(SPDF[SPDF@data$Attribute=="from",], col=2, add=T)
# plot(SPDF[ind1,], col=2, add=T)
plot(SPDF[SPDF@data$Attribute=="to",], col=4, add=T)