问题描述
我希望在同一调用中使用dataframe
和Inf
过滤掉NA
和filter
的行,并弃用c_across
:
filter_if
我可以使用library(dplyr)
df <- tibble(a = c(1,2,3,NA,1),b = c(5,Inf,8,3),c = c(9,10,11,12),d = c('a','b','c','d','e'),e = c(1,4,-Inf))
# # A tibble: 5 x 5
# a b c d e
# <dbl> <dbl> <dbl> <chr> <dbl>
# 1 1 5 9 a 1
# 2 2 Inf 10 b 2
# 3 3 8 Inf c 3
# 4 NA 8 11 d 4
# 5 1 3 12 e -Inf
或c_across
在两个呼叫中做到这一点:
filter_if
在一次调用df %>%
rowwise %>%
filter(!any(is.infinite(c_across(where(is.numeric))))) %>%
filter(!any(is.na(c_across(where(is.numeric)))))
# # A tibble: 1 x 5
# # Rowwise:
# a b c d e
# <dbl> <dbl> <dbl> <chr> <dbl>
# 1 1 5 9 a 1
#OR filter_if:
df %>%
filter_if(~is.numeric(.),all_vars(!is.infinite(.))) %>%
filter_if(~is.numeric(.),all_vars(!is.na(.)))
# # A tibble: 1 x 5
# a b c d e
# <dbl> <dbl> <dbl> <chr> <dbl>
# 1 1 5 9 a 1
(和filter
)中,我将如何使用两种方法?可能也有一种filter_if
方法?
谢谢
解决方法
我建议使用across()
中的dplyr
:
library(dplyr)
#Data
df <- tibble(a = c(1,2,3,NA,1),b = c(5,Inf,8,3),c = c(9,10,11,12),d = c('a','b','c','d','e'),e = c(1,4,-Inf))
#Mutate
df %>% filter(across(c(a:e),~ !is.na(.) & !is.infinite(.)))
输出:
# A tibble: 1 x 5
a b c d e
<dbl> <dbl> <dbl> <chr> <dbl>
1 1 5 9 a 1
,
尝试一下。使用位置标识数字列。
df %>%
filter(across(.cols = where(is.numeric),.fns = ~!is.infinite(.x) & !is.na(.x)))