【问题标题】:Remove list elements that are zero-row tibbles删除零行小标题的列表元素
【发布时间】: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 日创建。

【问题讨论】:

    标签: r tidyverse purrr


    【解决方案1】:

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

    【讨论】:

    • discard( ~ nrow(.x) == 0) 更精简'versey 的东西
    猜你喜欢
    • 1970-01-01
    • 2022-07-25
    • 1970-01-01
    • 1970-01-01
    • 2015-08-03
    • 1970-01-01
    • 2021-08-14
    • 2022-01-18
    • 1970-01-01
    相关资源
    最近更新 更多