【发布时间】:2018-09-16 16:40:07
【问题描述】:
我有一个 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 年 4 月 6 日创建。
【问题讨论】: