删除 zero-row 个小标题的列表元素

Remove list elements that are zero-row tibbles

我有一个 tibbles 列表。我正在尝试过滤所有 tibbles 共有的列,然后删除所有以零行结尾的 tibbles(但在技术上不是空的,因为它们有列)。似乎 purrr:::compact() 就是为此目的而设计的,但我认为我没有完全正确。有更好的解决方案吗?

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.

reprex package (v0.2.0) 创建于 2018-04-06。

您正在尝试使用 compact,但这只会过滤掉 NULL 个元素。要过滤掉零行元素,可以使用 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.