[英]How i can calculate a function across all columns with one column but all the other column that have no NA and no 0, using dplyr?
[英]How can I filter rows that are all NA using dplyr `across()` syntax?
如果列子集中的所有值都是NA
我想過濾我的數據。
我在這里找到了一個適用於所有列的答案,但在這種情況下,我想從過濾器操作中排除“包裝器”列。
library(dplyr)
df <- tibble(a = letters[1:3], b = c(NA, NA, 3), c = c(NA, 2, 3), d = letters[1:3])
# works, but I've lost my surrounding columns
df %>%
select(-one_of(c("a", "d"))) %>%
filter_all(any_vars(!is.na(.)))
# only works if all columns are all not NA (or vice versa), I've lost my partially NA rows
df %>%
filter(across(-one_of(c("a", "d")),
~ !is.na(.)))
期望的結果:
> df[2:3,]
# A tibble: 2 x 4
a b c d
<chr> <dbl> <dbl> <chr>
1 b NA 2 b
2 c 3 3 c
在以前版本的dplyr
您可以這樣使用filter_at
:
library(dplyr)
df %>% filter_at(vars(-one_of(c("a", "d"))), any_vars(!is.na(.)))
across
沒有直接替換any_vars
所以一種方法是在這里使用Reduce
:
df %>% filter(Reduce(`|`, across(-one_of(c("a", "d")),~!is.na(.))))
# A tibble: 2 x 4
# a b c d
# <chr> <dbl> <dbl> <chr>
#1 b NA 2 b
#2 c 3 3 c
一種選擇可能是:
df %>%
rowwise() %>%
filter(sum(!is.na(c_across(-all_of(c("a", "d"))))) != 0)
a b c d
<chr> <dbl> <dbl> <chr>
1 b NA 2 b
2 c 3 3 c
我在vignette("colwise", package = "dplyr")
發現了一個類似的例子
rowAny <- function(x) rowSums(x) > 0
df %>% filter(rowAny(across(-c(a,d), ~ !is.na(.))))
# A tibble: 2 x 4
a b c d
<chr> <dbl> <dbl> <chr>
1 b NA 2 b
2 c 3 3 c
但我會使用它,因為它更具可讀性:
rowAll <- function(x) rowSums(x) == length(x)
df %>% filter(!rowAll(across(-c(a,d), is.na)))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.