保留Na为< =总变量的20%的观测值

发布于 2025-01-18 13:53:39 字数 806 浏览 3 评论 0原文

假设我们有一个包含六个观测值和四个变量的数据框

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))
abcd
1NA16
NANA27
NANA3NA
4NA4NA
NANANA4
5164

我们如何保留 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))
abcd
1NA16
NANA27
NANA3NA
4NA4NA
NANANA4
5164

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

风筝在阴天搁浅。 2025-01-25 13:53:39

您可以使用 rowSums() 来计算每行中的 NA。然后丢弃行中 NA 超过 threshold*ncol(df) 的行。

threshold <- 0.5

df <- df[-which(rowSums(is.na(df)) > threshold*ncol(df)), ]

You use rowSums() to count up the NAs in each row. Then you discard the rows with more than threshold*ncol(df) NAs in their row.

threshold <- 0.5

df <- df[-which(rowSums(is.na(df)) > threshold*ncol(df)), ]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文