内部通过非sf列连接两个sf对象

时间:2018-02-28 14:45:04

标签: r join geometry gis sf

我尝试使用内连接或左连接来连接两个sf数据帧。这些数据框内部都有几何列。我一直收到错误:
check_join(x,y)出错:   y应该是data.frame;对于空间连接,请使用st_joinFALSE

下面的可重复示例:

df1 <- data.frame(
  var = c("a", "b", "c"),
  lon1 = c(20,35,45),
  lat1 = c(50,10,15)
) %>% st_as_sf(coords = c("lon1", "lat1"), dim = "XY") %>%
  st_set_crs(4326)

df2 <- data.frame(
  var = c("a", "b", "c"),
  lon2 = c(15,25,35),
  lat2 = c(5,10,15)
) %>% st_as_sf(coords = c("lon2", "lat2"), dim = "XY") %>%
  st_set_crs(4326)

df <- inner_join(df1, df2, by = "var")

我不想放弃几何体,因为我认为之后可能会弄乱我的结果,但欢迎任何解决方案

1 个答案:

答案 0 :(得分:3)

如果您只想进行非空间连接但是向前移动几何列,则可以“停用”&#39;首先(例如as.data.frame()),加入,然后重新激活&#39;要激活的几何列。您现在在data.frame中有两个sfc列,但是&#39; geometry.x&#39;是活跃的。

df <- inner_join(df1 %>% as.data.frame(), df2 %>% as.data.frame(), by = "var")

df %<>% st_sf(sf_column_name = 'geometry.x')

> str(df)
Classes ‘sf’ and 'data.frame':  3 obs. of  3 variables:
 $ var       : Factor w/ 3 levels "a","b","c": 1 2 3
 $ geometry.x:sfc_POINT of length 3; first list element: Classes 'XY', 'POINT', 'sfg'  num [1:2] 20 50
 $ geometry.y:sfc_POINT of length 3; first list element: Classes 'XY', 'POINT', 'sfg'  num [1:2] 15 5
 - attr(*, "sf_column")= chr "geometry.x"
 - attr(*, "agr")= Factor w/ 3 levels "constant","aggregate",..: NA NA
  ..- attr(*, "names")= chr  "var" "geometry.y"

> st_crs(df)
    Coordinate Reference System:
      EPSG: 4326 
      proj4string: "+proj=longlat +datum=WGS84 +no_defs"