gpt4 book ai didi

r - 使用 filter() 和 cross() 保留包含任何变量缺失值的数据帧的所有行

转载 作者:行者123 更新时间:2023-12-03 14:39:10 25 4
gpt4 key购买 nike

有时我想查看数据框中的所有行,如果我删除任何变量的所有缺失值的行,这些行将被删除。在这种情况下,我对如何使用 dplyr 执行此操作特别感兴趣。 1.0 across() filter() 内部使用的函数动词。

这是一个示例数据框:

df <- tribble(
~id, ~x, ~y,
1, 1, 0,
2, 1, 1,
3, NA, 1,
4, 0, 0,
5, 1, NA
)

tidyverse website 上提供了用于保留不包含任何缺失值的行的代码。 .具体来说,我可以使用:
df %>% 
filter(
across(
.cols = everything(),
.fns = ~ !is.na(.x)
)
)

返回:
# A tibble: 3 x 3
id x y
<dbl> <dbl> <dbl>
1 1 1 0
2 2 1 1
3 4 0 0

但是,我不知道如何返回相反的结果——任何变量中都有缺失值的行。我正在寻找的结果是:
# A tibble: 2 x 3
id x y
<dbl> <dbl> <dbl>
1 3 NA 1
2 5 1 NA

我的第一个想法就是删除 ! :
df %>% 
filter(
across(
.cols = everything(),
.fns = ~ is.na(.x)
)
)

但是,它返回零行。

当然,如果我提前知道所有具有缺失值的变量,我可以通过这段代码得到我想要的答案:
df %>% 
filter(is.na(x) | is.na(y))

但是,我正在寻找一种不需要我提前知道哪些变量具有缺失值的解决方案。此外,我知道如何使用 filter_all() 来做到这一点。功能:
df %>% 
filter_all(any_vars(is.na(.)))

但是, filter_all()函数已被 across() 的使用取代在现有动词中。见 https://dplyr.tidyverse.org/articles/colwise.html

我所做的其他不成功的尝试是:
df %>% 
filter(
across(
.cols = everything(),
.fns = ~any_vars(is.na(.x))
)
)

df %>%
filter(
across(
.cols = everything(),
.fns = ~!!any_vars(is.na(.x))
)
)

df %>%
filter(
across(
.cols = everything(),
.fns = ~!!any_vars(is.na(.))
)
)

df %>%
filter(
across(
.cols = everything(),
.fns = ~any(is.na(.x))
)
)

df %>%
filter(
across(
.cols = everything(),
.fns = ~any(is.na(.))
)
)

最佳答案

现在可以使用 dplyr 1.0.4.新款if_any()替换 across()对于过滤用例。

library(dplyr)

df <- tribble(~ id, ~ x, ~ y,
1, 1, 0,
2, 1, 1,
3, NA, 1,
4, 0, 0,
5, 1, NA)

df %>%
filter(if_any(everything(), is.na))
#> # A tibble: 2 x 3
#> id x y
#> <dbl> <dbl> <dbl>
#> 1 3 NA 1
#> 2 5 1 NA
创建于 2021-02-10 由 reprex package (v0.3.0)
详情请看这里: https://www.tidyverse.org/blog/2021/02/dplyr-1-0-4-if-any/

关于r - 使用 filter() 和 cross() 保留包含任何变量缺失值的数据帧的所有行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62161460/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com