从抽样列表中删除空的 tibble 列表

Remove empty tibble lists from sampling lists

我对重采样列表应用了 RNN,五分之三的列表没有产生预测,我想删除空列表。

# A tibble: 5 x 3
  splits          id     predict          
  <list>          <chr>  <list>           
1 <split [24/12]> Slice1 <tibble [48 × 3]>
2 <split [24/12]> Slice2 <tibble [48 × 3]>
3 <split [24/12]> Slice3 <lgl [1]>        
4 <split [24/12]> Slice4 <lgl [1]>        
5 <split [24/12]> Slice5 <lgl [1]>  

因此尝试使用 discard() 或 Filter() 删除列表 3、4、5,但我无法从 tibbles 中提取列表子集。

> discard(sample_predictions, ~nrow(.) == 0)
Error: Predicate functions must return a single `TRUE` or `FALSE`, not a logical vector of length 0
Backtrace:
 1. purrr::discard(sample_predictions, ~nrow(.) == 0)
 2. purrr:::probe(.x, .p, ...)
 3. purrr::map_lgl(.x, .p, ...)
 4. purrr:::.f(.x[[i]], ...)

> Filter(function(x) dim[x]>0,sample_predictions )
Error in dim[x] : object of type 'builtin' is not subsettable

在这里,我们可以使用map。根据显示的数据,某些 list 元素是 length 1 的逻辑向量,而不是 tibble。一个选项是 filter 通过使用 map 遍历 list 并检查它是否是小标题 (is_tibble)

library(dplyr)
library(purrr)
sample_predictions %>% 
          filter(map_lgl(predict, is_tibble))

或使用base R

sample_predictions[sapply(sample_predictions$predict, Negate(is.logical)),]

数据

sample_predictions <- tibble(predict = list(tibble(col1 = 1:5), 
        tibble(col1 = 1:3), TRUE))