根据整行使用dplyr / magrittr过滤行 [英] Filter rows with dplyr/magrittr based on entire row

查看:78
本文介绍了根据整行使用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 rowMeans 。提供的数据的示例:

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

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

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

# with rowMeans:
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,]

以获得相同的结果。

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

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