【发布时间】:2018-09-12 18:58:05
【问题描述】:
尝试将函数应用于嵌套数据框。数据样本:
# required packages
library(dplyr)
library(sf)
library(tidyr)
library(purrr)
# sample data
ln1 <- data.frame(
id = c(1,1,2,2),
lon = c(1,4,4,9),
lat = c(2,9,9,5)
)
ln2 <- data.frame(
id = c(1,1,2,2),
lon = c(3,3,6,6),
lat = c(15,0,15,0)
)
# function for creating an "sf" object
make_sf_lns <- function(x) {
x %>% st_as_sf(coords = c("lon", "lat"), dim = "XY") %>%
st_set_crs(4326) %>%
group_by(id) %>% summarise(geometry = st_union(geometry)) %>%
st_cast("LINESTRING")
}
# converting data to "sf" objects - "LINESTRING"s
ln1 <- make_sf_lns(ln1)
ln2 <- make_sf_lns(ln2)
以下代码行代表我打算做的事情:
st_intersection(ln1, ln2)
但出于特定原因,我需要将st_intersection 应用于嵌套数据框,如下所示:
# implementation with `tidyr::nest` and `purrr::map2`
ln1 <- ln1 %>% group_by(id) %>% nest()
map2(ln1$data, ln2, ~ st_intersection(.x, .y))
当我这样做时,预期的结果是一个带有交叉点的嵌套数据框,但会出现以下错误:
Error in st_crs(x) == st_crs(y) : Expecting a single value: [extent=2].
In addition: Warning message:
In if (is.na(x)) NA_crs_ else if (inherits(x, "crs")) x else if
(is.numeric(x)) CPL_crs_from_epsg(as.integer(x)) else if (is.character(x)) { :
the condition has length > 1 and only the first element will be used
【问题讨论】: