[英]How to conditionally subset a list using the purrr package
我有以下列表:
x <- list(1:5, 1:10)
x
#> [[1]]
#> [1] 1 2 3 4 5
#> [[2]]
#> [1] 1 2 3 4 5 6 7 8 9 10
並且只想選擇包含10的元素。
期望的結果:
#> [[1]]
#> [1] 1 2 3 4 5 6 7 8 9 10
我怎樣才能做到這一點簡潔,在使用管道運營商和purrr包單行 ?
這個人。 代碼有效,但感覺有點笨拙。
x %>% map_lgl(~contains(.,10L)) %>% subset(x,.)
有沒有更好的方法使用x
和管道操作符每一次?
你可以使用purrr::keep
library(purrr)
x <- list(1:5, 1:10)
x
#> [[1]]
#> [1] 1 2 3 4 5
#>
#> [[2]]
#> [1] 1 2 3 4 5 6 7 8 9 10
x %>% keep(~ 10 %in% .x)
#> [[1]]
#> [1] 1 2 3 4 5 6 7 8 9 10
x[sapply(x, function(x) any(x == 10))]
我們可以使用Filter
Filter(function(x) 10 %in% x, x)
#[[1]]
#[1] 1 2 3 4 5 6 7 8 9 10
或者用purrr
x %>%
purrr::map_lgl(~10 %in% .) %>%
x[.]
我們可以使這個功能
filterL <- function(lst, val){
lst %>%
purrr::map_lgl(~val %in% .) %>%
lst[.]
}
filterL(x, 10)
#[[1]]
# [1] 1 2 3 4 5 6 7 8 9 10
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.