Using the subset
, we create a logical index based on the 2nd and third columns.
subset(df, subset=!(val2==0|val3==0))
as subset
argument works on columns and not on matrices.
We can also use [
instead of subset
.
df[!(df[,2]==0|df[,3]==0),]
Regarding the second answer in the OP's post
df[,c(2,3)]!=0 #returns a matrix
# val2 val3
#[1,] TRUE TRUE
#[2,] FALSE FALSE
#[3,] TRUE TRUE
For subsetting rows, we need only a single logical index per each row.
Another option is rowSums
(if you want to remove rows that are 0 for both column 2 and 3)
df[rowSums(df[2:3])!=0,]
i.e.
df$val3[2] <- 2
will return all the rows with rowSums
while the other methods return rows 1 and 3.
The equivalent option with subset
is &
subset(df, !(val2==0 & val3==0))
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…