Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove list elements that are zero-row tibbles

Tags:

r

purrr

tidyverse

I have a list of tibbles. I'm trying to filter on a column common to all tibbles, and then remove any tibbles that end up with zero rows (but are not technically empty since they have columns). It seems like purrr:::compact() is intended for this purpose, but I don't think I've got it quite right. Is there a better solution?

require(tidyverse)
#> Loading required package: tidyverse
mylst <- lst(cars1 = cars %>% as.tibble(), cars2 = cars %>% as.tibble() %>% mutate(speed = speed + 100))

#This produces a list with zero-row tibble elements:
mylst %>% map(function(x) filter(x, speed == 125))
#> $cars1
#> # A tibble: 0 x 2
#> # ... with 2 variables: speed <dbl>, dist <dbl>
#> 
#> $cars2
#> # A tibble: 1 x 2
#>   speed  dist
#>   <dbl> <dbl>
#> 1  125.   85.

#This results in the same thing:
mylst %>% map(function(x) filter(x, speed == 125)) %>% compact()
#> $cars1
#> # A tibble: 0 x 2
#> # ... with 2 variables: speed <dbl>, dist <dbl>
#> 
#> $cars2
#> # A tibble: 1 x 2
#>   speed  dist
#>   <dbl> <dbl>
#> 1  125.   85.

#Putting compact inside the map function reduces $cars1 to 0x0, but it's still there:
mylst %>% map(function(x) filter(x, speed == 125) %>% compact())
#> $cars1
#> # A tibble: 0 x 0
#> 
#> $cars2
#> # A tibble: 1 x 2
#>   speed  dist
#>   <dbl> <dbl>
#> 1  125.   85.

#This finally drops the empty element, but seems clumsy. 
mylst %>% map(function(x) filter(x, speed == 125) %>% compact()) %>% compact()
#> $cars2
#> # A tibble: 1 x 2
#>   speed  dist
#>   <dbl> <dbl>
#> 1  125.   85.

Created on 2018-04-06 by the reprex package (v0.2.0).

like image 717
jzadra Avatar asked Dec 18 '22 00:12

jzadra


1 Answers

You are trying to use compact but this only filters out NULL elements. To filter out zero row elements, you can use discard:

mylst %>% 
    map(function(x) filter(x, speed == 125)) %>% 
    discard(function(x) nrow(x) == 0)
#$cars2
## A tibble: 1 x 2
#  speed  dist
#  <dbl> <dbl>
#1  125.   85.
like image 111
konvas Avatar answered Jan 11 '23 17:01

konvas