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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With