[英]Filter a nested list of dataframes based on logical vector in 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)),
class = "data.frame", row.names = c(NA, -3L)),
`61` = structure(list(lon = c(11.9464237941416, 11.9536554768081,11.9112311461624),
lat = c(48.040970408282, 48.0408864989903, 48.0284615642167)),
class = "data.frame", row.names = c(NA, -3L )),
`71` = structure(list(lon = c(11.9274864543974, 11.8733675039864,11.933264512569),
lat = c(48.0135478382282, 48.0216452485664, 48.0289752363299)),
class = "data.frame", row.names = c(NA, -3L)),
`81` = structure(list(lon = c(11.8837173493491, 11.9072450330566,11.8943898749275),
lat = c(48.0266639859759, 48.0132853717376, 48.0327326995006)),
class = "data.frame", row.names = c(NA, -3L )),
`91` = structure(list(lon = c(11.882538477087, 11.8377742591454,11.8817027393128),
lat = c(48.0284081468982, 48.022864811514, 48.0229810559649)),
class = "data.frame", row.names = c(NA, -3L )))
我想根據嵌套的邏輯值列表過濾此列表。
index <- list(`41` = c(TRUE, TRUE, FALSE), `51` = c(FALSE, FALSE, TRUE
), `61` = c(FALSE, FALSE, FALSE), `71` = c(FALSE, FALSE, FALSE
), `81` = c(FALSE, FALSE, FALSE), `91` = c(FALSE, 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))
這個答案可以很好地將列表轉換為數據框。 如果順序一致,那么我認為這就是您所需要的
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, ~as.data.frame(.x), .id="id")
# filter coordinates on the values in index
coords_df[index_df$.x,]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.