如何使用 sf 遍历值列表并将其添加到空间参数内代码的指定区域?

How to loop through a list of values and add it in the designated areas of the code within spatial parameters using sf?

这个问题建立在我的 的基础上。

我有一个列表c("String1","String2","String3")

没有循环,代码如下所示

Data_String1<- DF2 %>%
mutate(`New String`= if_else(lengths(st_intersects(DF2, DataFrame_String1, join = st_within))>0,DataFrame_String1$ID,"N"))%>%
filter(.,`New String`!="N")

Data_String2<- DF2 %>%
mutate(`New String`= if_else(lengths(st_intersects(DF2, DataFrame_String2, join = st_within))>0,DataFrame_String2$ID,"N"))%>%
filter(.,`New String`!="N")

Data_String3<- DF2 %>%
mutate(`New String`= if_else(lengths(st_intersects(DF2, DataFrame_String3, join = st_within))>0,DataFrame_String3$ID,"N"))%>%
filter(.,`New String`!="N")

使用我在此处尝试实现的先前代码中显示的解决方案的原理:

lst1 <- map(c("String1", "String2", "String3") ~DF2 %>%
    mutate(`New String`= if_else(lengths(st_intersects(DF2, c("String1","String2","String3"), join = st_within)) > 0, .x, "N")) %>%
    filter(.,`New String`!="N")

但是我收到这样的错误消息

x no applicable method for 'st_geometry' applied to an object of class "character"` which makes me wonder if the dataframe loses being an spatial entity.

简单地从以前的解决方案扩展:

df_lst <- map(c("String1", "String2", "String3"), ~ DataFrame %>% 
    filter(ID == .x)
)

DF2_subs <- map(df_lst, ~ DF2 %>% 
    mutate(`New String`= if_else(
        lengths(st_intersects(DF2, .x, join = st_within)) > 0,
        .x$ID,
        "N")) %>%
    filter(`New String`!="N")
)

否则传入实际数据帧而不是字符串向量

DF2_subs <- map(list(Data_String1, Data_String2, Data_String3), ~ DF2 %>% 
    mutate(`New String`= if_else(
        lengths(st_intersects(DF2, .x, join = st_within)) > 0,
        .x$ID,
        "N")) %>%
    filter(`New String`!="N")
)