簡體   English   中英

R - 將兩組坐標轉換為空間點數據幀

[英]R - Converting two sets of coordinates to Spatial Point Data Frame

我有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)

我提前道歉,誤解了你的問題並做了錯誤的編輯。
coords應該是一個matrixdata.frame ,而nrow(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)
將帖子

您可以使用其data.frame過濾SpatialPointsDataFrame數據。

 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) 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM