保留Na为< =总变量的20%的观测值
假设我们有一个包含六个观测值和四个变量的数据框
df <- data.frame(a = c(1, NA, NA, 4, NA, 5),
b = c(NA, NA, NA, NA, NA, 1),
c = c(1, 2, 3, 4, NA, 6),
d = c(6, 7, NA, NA, 4, 4))
a | b | c | d |
---|---|---|---|
1 | NA | 1 | 6 |
NA | NA | 2 | 7 |
NA | NA | 3 | NA |
4 | NA | 4 | NA |
NA | NA | NA | 4 |
5 | 1 | 6 | 4 |
我们如何保留 NA 不超过 50 的观测值变量的百分比? (在这种情况下,剩下的每个观测值最多有两个 NA;因此只会保留 4 个观测值。)
Suppose we have this dataframe with six observations and four variables
df <- data.frame(a = c(1, NA, NA, 4, NA, 5),
b = c(NA, NA, NA, NA, NA, 1),
c = c(1, 2, 3, 4, NA, 6),
d = c(6, 7, NA, NA, 4, 4))
a | b | c | d |
---|---|---|---|
1 | NA | 1 | 6 |
NA | NA | 2 | 7 |
NA | NA | 3 | NA |
4 | NA | 4 | NA |
NA | NA | NA | 4 |
5 | 1 | 6 | 4 |
How can we retain observations whose NA's does not exceed 50% of the variables? (In this case each observation left will have two NA's at most; thus only 4 observations will be retained.)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用 rowSums() 来计算每行中的 NA。然后丢弃行中 NA 超过
threshold*ncol(df)
的行。You use
rowSums()
to count up the NAs in each row. Then you discard the rows with more thanthreshold*ncol(df)
NAs in their row.