删除零行元素的列表元素

jza*_*dra 2 r purrr tidyverse

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

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

kon*_*vas 11

您正在尝试使用,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.
Run Code Online (Sandbox Code Playgroud)

  • 并且`discard(~nrow(.x)== 0)`以获得更精简的'versey东西' (6认同)