通过非 sf 列内部连接两个 sf 对象
Inner-Joining two sf objects by non sf column
我正在尝试使用内连接或左连接连接两个 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")
我不想放弃几何体,因为我认为这会弄乱我的结果,但欢迎任何解决方案
如果您只想进行 non-spatial 连接但将几何列向前移动,您可以先 'deactivate' 它们(例如 as.data.frame()),连接,然后 'reactivate' 您想要激活的几何列。现在,您的 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"
我正在尝试使用内连接或左连接连接两个 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")
我不想放弃几何体,因为我认为这会弄乱我的结果,但欢迎任何解决方案
如果您只想进行 non-spatial 连接但将几何列向前移动,您可以先 'deactivate' 它们(例如 as.data.frame()),连接,然后 'reactivate' 您想要激活的几何列。现在,您的 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"