基于整行,在R中使用dplyr / magrittr过滤行 [英] Filter rows with dplyr/magrittr in R based on entire row

查看:133
本文介绍了基于整行,在R中使用dplyr / magrittr过滤行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个可以使用 filter 使用dplyr过滤行,但条件通常基于每行的特定列,例如

One is able to filter rows with dplyr with filter, but the condition is usually based on specific columns per row such as

d <- data.frame(x=c(1,2,NA),y=c(3,NA,NA),z=c(NA,4,5))
d %>% filter(!is.na(y))

我想通过NA的数量是否大于50%来过滤这个行,例如

I want to filter the row by whether the number of NA is greater than 50%, such as

d %>% filter(mean(is.na(EACHROW)) < 0.5 )

推荐答案

您可以使用 rowSums 为了那个原因。提供的数据的示例:

You could use rowSums for that. An example with the provided data:

> d
   x  y  z
1  1  3 NA
2  2 NA  4
3 NA NA  5

d %>% filter(rowSums(is.na(.))/ncol(.) < 0.5)
# or:
d %>% filter(rowMeans(is.na(.)) < 0.5)

其中:

  x  y  z
1 1  3 NA
2 2 NA  4

正如你可以看到第3行从数据中删除。

As you can see row 3 is removed from the data.

在基数R中,您可以执行以下操作:

In base R, you could just do:

d[rowMeans(is.na(d)) < 0.5,]

获得相同的结果。

这篇关于基于整行,在R中使用dplyr / magrittr过滤行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆