删除零行元素的列表元素

时间:2018-04-06 15:37:48

标签: r tidyverse purrr

我有一个单词列表。我正在尝试过滤所有元素共有的列,然后删除最终为零行的任何元素(但由于它们有列,因此在技术上不是空的)。似乎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。

1 个答案:

答案 0 :(得分:8)

您正在尝试使用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.