省略许多特定列中带有0的行

问题描述

我有一个非常广泛的数据集,具有多个心理量表,如果少数列的任何包含零(即缺少响应),我想删除行。

我知道当数据帧较小时该怎么做,但是我的方法不可扩展。例如,

dftry <- data.frame(x = c(1,2,5,3,0),y = c(0,10,37),z=c(12,33,22,23))
  x  y  z
1 1  0 12
2 2 10  0
3 5  5 33
4 3  3 22
5 0 37 23
# Remove row if it has 0 in y or z columns
# is there a difference between & and,? 
dftry %>% filter(dftry$y > 0 & dftry$z > 0)
  x  y  z
1 5  5 33
2 3  3 22
3 0 37 23

在我的实际数据中,如果这些列中的任何一个为零,我想删除行:

# this is the most succinct way of selecting the columns in question
select(c(1:42,contains("BMIS"),"hamD","GAD"))

解决方法

您可以使用rowSums

cols <- c('y','z')
dftry[rowSums(dftry[cols] == 0,na.rm = TRUE) == 0,]

#  x  y  z
#1 5  5 33
#2 3  3 22
#3 0 37 23

我们可以根据您的实际使用情况将其集成到dplyr中。

library(dplyr)

dftry %>%
  filter(rowSums(select(.,c(1:42,contains("BMIS"),"hamD","GAD")) == 0,na.rm = TRUE) == 0)
,

使用dplyr进行这项工作吗?

> library(dplyr)
> dftry
  x  y  z a  b  c BMIS_1 BMIS_3 hamD GAD  m  n
1 1  0 12 1  0 12      1      0   12  12 12 12
2 2 10  0 2 10  0      2     10    0   0  0  0
3 5  5 33 5  5 33      5      5   33  33 33 33
4 3  3 22 3  3 22      3      3   22  22 22 22
5 0 37 23 0 37 23      0     37   23  23 23 23
> dftry %>% select(c(1:3,contains('BMIS'),hamD,GAD)) %>%  filter_all(all_vars(. != 0))
  x y  z BMIS_1 BMIS_3 hamD GAD
1 5 5 33      5      5   33  33
2 3 3 22      3      3   22  22
> 

使用的数据:

> dftry
  x  y  z a  b  c BMIS_1 BMIS_3 hamD GAD  m  n
1 1  0 12 1  0 12      1      0   12  12 12 12
2 2 10  0 2 10  0      2     10    0   0  0  0
3 5  5 33 5  5 33      5      5   33  33 33 33
4 3  3 22 3  3 22      3      3   22  22 22 22
5 0 37 23 0 37 23      0     37   23  23 23 23

> dput(dftry)
structure(list(x = c(1,2,5,3,0),y = c(0,10,37),z = c(12,33,22,23),a = c(1,b = c(0,c = c(12,BMIS_1 = c(1,BMIS_3 = c(0,hamD = c(12,GAD = c(12,m = c(12,n = c(12,23)),class = "data.frame",row.names = c(NA,-5L))
> 

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...