簡體   English   中英

如何使用purrr包有條件地對列表進行子集化

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM