使用 "and" 条件 (R) 对数据帧进行子集化

Subsetting a dataframe with the "and" condition (R)

我将数据框定义为:

df <- data.frame(c(1,0,4,0,4),c(3,2,0,0,2))
names(df) <- c("A","B")

其中:

> df
  A B
1 1 3
2 0 2
3 4 0
4 0 0
5 4 2

现在我只想获取 "not completely null" 行。我是这样做的:

df_notNull <- subset(df,df$A!=0 & df$B!=0)
> df_notNull
      A B
    1 1 3
    5 4 2

显然我没有得到我想要的。问题不是 "and" 条件,因为我只想在有两个零时忽略这些行(所以 "and")。我必须用不同的方式来写吗?

df[rowSums(df) != 0,]
#  A B
#1 1 3
#2 0 2
#3 4 0
#5 4 2

当两者都不为 0 时,您用代码讲述的内容是 slecet。因此,使用 |(或)而不是 & 或以不同的方式使用 !

df_notNull <- subset(df,df$A!=0 | df$B!=0)

df_notNull <- subset(df,!(df$A==0 & df$B==0))

正如@Frank 所建议的,您不需要df$

df_notNull <- subset(df,A!=0 | B!=0)
df_notNull <- subset(df,!(A==0 & B==0))

我们可以使用 Reduce+

df[!!Reduce(`+`, df),]
#  A B
#1 1 3
#2 0 2
#3 4 0
#5 4 2