【问题标题】:Remove empty tibble lists from sampling lists从采样列表中删除空的 tibble 列表
【发布时间】:2020-11-18 20:58:24
【问题描述】:

我对重采样列表应用了 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

【问题讨论】:

    标签: r tibble


    【解决方案1】:

    在这里,我们可以使用map。根据显示的数据,一些list 元素是length 1 的逻辑向量,而不是tibble。一个选项是 filter 通过循环 listmap 并检查它是否是一个 tibble (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))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-01-06
      • 2017-11-02
      • 2022-11-01
      • 2016-02-17
      • 2021-08-21
      • 1970-01-01
      • 1970-01-01
      • 2021-05-13
      相关资源
      最近更新 更多