如何解决R:过滤许多但不是全部列上的非缺失数据 数据
有以下数据框,我们称之为df
,观察如下
id | b | c | f | e_7 | ic_107 | d | g | j |
---|---|---|---|---|---|---|---|---|
1 | 23 | 3 | 66 | 97 | 8 | 5 | 7 | 0 |
2 | 1 | 1 | 5 | 7 | 不适用 | 不适用 | 不适用 | 不适用 |
3 | 不适用 | 2 | 79 | 5 | 5 | 4 | 9 | 0 |
4 | 0 | 2 | 32 | 1 | 6 | 6 | 1 | 0 |
5 | 36 | 6 | 9 | 49 | 9 | 不适用 | 不适用 | 不适用 |
6 | 0 | 2 | 32 | 1 | 6 | 7 | 8 | 9 |
7 | 36 | 不适用 | 不适用 | 49 | 9 | 0 | 0 | 1 |
我只想保留许多列中没有 NA 的记录,但不是所有列。比方说,b、c、d、g 和 j 列。
我目前将 filter
与 pipes
一起使用,但我想避免编码如下:
df_new <- df %>%
filter(!is.na(b))%>%
filter(!is.na(c))%>%
filter(!is.na(d))%>%
filter(!is.na(g))%>%
filter(!is.na(j))
有没有更简单的方法来编写代码?
在这个例子中,我有 5 列用于过滤条件。在我的真实数据集中,我有 17 个。因此,我想避免上面的编码。
另外,不是简单的列名a
,b
,c
,d
...,我真实数据集的列有很长的名字,比如{ {1}}、lighteningdate
、depression
...,所以我想在编码中使用列号向量 (anxiety
) 而不是列名列表。
解决方法
我们可以将 filter
与 if_all
一起使用
library(dplyr)
library(purrr)
df %>%
filter(if_all(c(b,c,d,g,j),negate(is.na)))
# id b c f e_7 ic_107 d g j
#1 1 23 3 66 97 8 5 7 0
#2 4 0 2 32 1 6 6 1 0
#3 6 0 2 32 1 6 7 8 9
或者指定索引
df %>%
filter(if_all(c(2:3,7:9),~ !is.na(.)))
或者用complete.cases
df %>%
filter(if_all(c(2:3,complete.cases))
类似于 base R
选项
df[complete.cases(df[c(2:3,7:9)]),]
数据
df <- structure(list(id = 1:7,b = c(23L,1L,NA,0L,36L,36L),c = c(3L,2L,6L,NA),f = c(66L,5L,79L,32L,9L,e_7 = c(97L,7L,49L,49L),ic_107 = c(8L,9L),d = c(5L,4L,0L
),g = c(7L,8L,0L),j = c(0L,1L)),class = "data.frame",row.names = c(NA,-7L
))
,
使用 subset
+ is.na
+ rowMeans
的另一个基本 R 选项
> subset(df,!is.na(rowMeans(cbind(b,j))))
id b c f e_7 ic_107 d g j
1 1 23 3 66 97 8 5 7 0
4 4 0 2 32 1 6 6 1 0
6 6 0 2 32 1 6 7 8 9
,
你可以试试这个:
library(dplyr)
library(purrr)
df <- tribble(~id,~b,~c,~f,~e_7,~ic_107,~d,~g,~j,1,23,3,66,97,8,5,7,2,79,4,9,32,6,36,49,1)
df %>% filter(map_int(split(is.na(select(df,b,j)),1:nrow(df)),sum)<=2L)
,
您可以使用across(c(.,.,.))
:
library(dplyr)
df %>%
filter(across(c(a,c),~ !is.na(.)))
a b c d
1 2 5 10 NA
2 3 6 7 3
模拟数据:
df <- data.frame(
a = c(NA,b = c(4,7),c = c(8,10,6),d = c(NA,7)
)
,
您可以使用 const item = {
accountsUrl: 'www.google.com',accountsDomain: 'www.yahoo.com'
}
const regex = /\$ENV\[(\w+)]/
let s = "foo$ENV[accountsDomain]bar";
s = s.replace(regex,(m,g1) => item[g1] || m);
console.log(s);
计算每行中 rowSums
值的数量,并仅选择那些没有 NA
的行。
NA
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。