5

我正在尝试使用内连接或左连接来连接两个 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")

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

4

1 回答 1

9

如果您只想进行非空间连接但将几何列向前移动,您可以先“停用”它们(例如 as.data.frame()),连接,然后“重新激活”您想要的几何列积极的。您现在在 data.frame 中有两个 sfc 列,但“geometry.x”是活动的。

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"
于 2018-02-28T17:48:33.553 回答