R坐标函数 - 指定两对空间坐标

时间:2015-07-02 09:16:12

标签: r

我有一个数据框,我希望推广到空间数据,但它有两对坐标 - 旅程起源军械测量网格参考和旅程目的地军械测量网格参考。

所以我想将数据框推广到空间然后重新投影到WGS84。我可以用一对坐标来做到这一点:

# promote data frame to spatial
coordinates(myvar) = ~Easting + Northing
# give it the OS projection
proj4string(myvar)=CRS("+init=epsg:27700")
# convert projection to WGS84 as used by osm
myvar.WGS84 <- spTransform(myvar, CRS("+init=epsg:4326"))

但我怎么能用两对呢?

编辑 - 我已经通过拆分数据框并按照下面的代码重新加入来实现它,但肯定必须有一种更有效和更优雅的方式:

#create separate object for destination and Dest grid refs
 destgridrefs <- mydata %>% select(-Origin_Easting, -Origin_Northing)
 origingridrefs <-  mydata %>% select(rowID, Origin_Easting, Origin_Northing)
#rename the columns
 destgridrefs <- destgridrefs %>% rename(lat=Dest_Easting, long=Dest_Northing)
 origingridrefs <- origingridrefs %>% rename(lat=Origin_Easting, long=Origin_Northing)
# make data frame
 destgridrefs <- as.data.frame(destgridrefs)
 origingridrefs <- as.data.frame(na.omit(origingridrefs))
# promote data frame to spatial
 coordinates(destgridrefs) = ~lat+long
 coordinates(origingridrefs) = ~lat+long
# give them the OS projection
 proj4string(destgridrefs)=CRS("+init=epsg:27700")
 proj4string(origingridrefs)=CRS("+init=epsg:27700")
# convert projection to WGS84
 destgridrefs.WGS84 <- spTransform(destgridrefs, CRS("+init=epsg:4326"))
 origingridrefs.WGS84 <- spTransform(origingridrefs, CRS("+init=epsg:4326"))
# then convert spatial points to a data frame so they can be used by ggplot
 destgridrefs.WGS84.df <- as.data.frame(destgridrefs.WGS84)
 origingridrefs.WGS84.df <- as.data.frame(origingridrefs.WGS84)
# join them together                                                    
 allgridrefs <- inner_join(destgridrefs.WGS84.df, origingridrefs.WGS84.df, by="rowID")

1 个答案:

答案 0 :(得分:1)

您可以将坐标对放在SpatialLines对象中。这里,一行是起始目的地对。以下代码是sp package documentation of SpatialLines

中的示例
# from the sp vignette:
l1 = cbind(c(1,2,3),c(3,2,2))
l1a = cbind(l1[,1]+.05,l1[,2]+.05)
l2 = cbind(c(1,2,3),c(1,1.5,1))
Sl1 = Line(l1)
Sl1a = Line(l1a)
Sl2 = Line(l2)
S1 = Lines(list(Sl1, Sl1a), ID="a")
S2 = Lines(list(Sl2), ID="b")
Sl = SpatialLines(list(S1,S2))
summary(Sl)
plot(Sl, col = c("red", "blue"))