r - 从表中删除 NULL 值
问题描述
我有一张表,其中有一列中有 NUll 值,这些空值添加到 Highchart 图中的 Extra Label 中。如何使用 Dplyr 操作数据以删除特定列中具有空值的行?
我正在考虑对后端 SQL 查询进行更改,并过滤结果以获得所需的输出。但这不是一个合适的方式。
这是行不通的,
dplyr::filter(!is.na(ColumnWithNullValues)) %>%
实际代码:
df <- data() %>%
dplyr::filter(CreatedBy == 'owner') %>%
dplyr::group_by(`Reason for creation`) %>%
dplyr::arrange(ReasonOrder) %>%
ColumnWithNullValues <- 此列具有 Null 值。
解决方案
这是一个小例子df:
library(dplyr)
library(purrr)
df <- tibble(
ColumnWithNullValues = list(c(1:5), NULL, c(6:10))
)
df
#> # A tibble: 3 x 1
#> ColumnWithNullValues
#> <list>
#> 1 <int [5]>
#> 2 <NULL>
#> 3 <int [5]>
在这种情况下,最合乎逻辑的可能似乎使用:
df %>%
filter(!is.null(ColumnWithNullValues))
#> # A tibble: 3 x 1
#> ColumnWithNullValues
#> <list>
#> 1 <int [5]>
#> 2 <NULL>
#> 3 <int [5]>
但正如你所看到的,这是行不通的。相反,我们需要使用 map/sapply/vapply 进入列表。例如像这样:
df %>%
filter(map_lgl(ColumnWithNullValues, function(x) !all(is.null(x))))
#> # A tibble: 2 x 1
#> ColumnWithNullValues
#> <list>
#> 1 <int [5]>
#> 2 <int [5]>
但正如@akrun hast 在评论中解释的那样,列表中的元素不可能包含NULL
其他值。所以我们可以将代码简化为:
df %>%
filter(!map_lgl(ColumnWithNullValues, is.null))
#> # A tibble: 3 x 1
#> ColumnWithNullValues
#> <list>
#> 1 <int [5]>
#> 2 <int [5]>