gpt4 book ai didi

r - 在多列上使用 any() 或 all() 和 is.na()

转载 作者:行者123 更新时间:2023-12-05 09:15:01 25 4
gpt4 key购买 nike

我想从我的数据集中删除所有 NA 的行(也就是保留具有任何非 NA 的行)以获取列列表。我如何更新此代码,以便将 xy 作为向量提供?这将使我能够灵活地添加和删除列以进行检查。

library(dplyr)

ds <-
tibble(
id = c(1:4),
x = c(NA, 1, NA, 4),
y = c(NA, NA , 3, 4)
)

ds %>%
rowwise() %>%
filter(
any(
!is.na(x),
!is.na(y)
)
) %>%
ungroup()

我正在尝试编写类似 any(!is.na(c(x,y))) 的内容,但我不确定如何为 is 提供多个参数。娜()

最佳答案

我们可以使用 filter_atany_vars

ds %>% 
filter_at(vars(x:y), any_vars(!is.na(.)))
# A tibble: 3 x 3
# id x y
# <int> <dbl> <dbl>
#1 2 1 NA
#2 3 NA 3
#3 4 4 4

-更新 - 2022 年 2 月 7 日

在新版本的dplyr中(如@GitHunter0所建议)可以使用if_all/if_anyacross

ds %>%
filter(if_any(x:y, complete.cases))
# A tibble: 3 × 3
id x y
<int> <dbl> <dbl>
1 2 1 NA
2 3 NA 3
3 4 4 4

关于r - 在多列上使用 any() 或 all() 和 is.na(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53307189/

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