如何解决根据R中的逻辑向量过滤数据帧的嵌套列表
我有一个嵌套的坐标列表:
coords <- list(`41` = structure(list(lon = c(11.9170235974052,11.9890348226944,11.9266305690725),lat = c(48.0539406017157,48.0618200883643,48.0734094557987)),class = "data.frame",row.names = c(NA,-3L )),`51` = structure(list(lon = c(11.9700157009047,11.9661664366154,11.9111812165745),lat = c(48.0524843177559,48.0645786453912,48.0623193233537)),-3L)),`61` = structure(list(lon = c(11.9464237941416,11.9536554768081,11.9112311461624),lat = c(48.040970408282,48.0408864989903,48.0284615642167)),`71` = structure(list(lon = c(11.9274864543974,11.8733675039864,11.933264512569),lat = c(48.0135478382282,48.0216452485664,48.0289752363299)),`81` = structure(list(lon = c(11.8837173493491,11.9072450330566,11.8943898749275),lat = c(48.0266639859759,48.0132853717376,48.0327326995006)),`91` = structure(list(lon = c(11.882538477087,11.8377742591454,11.8817027393128),lat = c(48.0284081468982,48.022864811514,48.0229810559649)),-3L )))
我想基于嵌套的逻辑值列表来过滤此列表。
index <- list(`41` = c(TRUE,TRUE,FALSE),`51` = c(FALSE,FALSE,TRUE
),`61` = c(FALSE,`71` = c(FALSE,FALSE
),`81` = c(FALSE,`91` = c(FALSE,FALSE))
这样做的最佳方法是什么? 我试图取消列出嵌套列表或创建一个data.frame,但没有成功。 谢谢!
解决方法
您可以像这样使用Map
:
Map(function(x,y) x[y,],coords,index)
#$`41`
# lon lat
#1 11.91702 48.05394
#2 11.98903 48.06182
#$`51`
# lon lat
#3 11.91118 48.06232
#$`61`
#[1] lon lat
#<0 rows> (or 0-length row.names)
#...
#...
在tidyverse
中:
library(purrr)
library(dplyr)
map2(coords,index,~.x %>% filter(.y))
,
This答案可以很好地将列表变成数据框。如果顺序一致,那么我认为这就是您所需要的
library(purrr)
# use solution to convert lists to dataframes,storing the names in id column
coords_df <- map_df(coords,~as.data.frame(.x),.id="id")
index_df <- map_df(index,.id="id")
# filter coordinates on the values in index
coords_df[index_df$.x,]
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。