rocknRrr
rocknRrr

Reputation: 421

Remove empty tibble lists from sampling lists

I applied RNN for the resampling lists, and three out of five lists didn't produce predictions, and want to remove the empty lists.

# 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]>  

So tried to remove the list 3,4,5 using discard() or Filter(), but I failed to subset list from 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

Upvotes: 1

Views: 150

Answers (1)

akrun
akrun

Reputation: 887531

Here, we could use map. Based on the data showed, some of the list elements are logical vector of length 1 instead of tibble. An option is to filter by looping over the list with map and check if it is a tibble (is_tibble)

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

Or using base R

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

data

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

Upvotes: 2

Related Questions