Manuel
Manuel

Reputation: 205

remove row if there are zeros in 2 specific columns (R)

I have a data frame like this

    col1 col2 col3 col4
row1   1   0     6    7
row2   5   7     0    6
row3   0   0     4    6

And I need to remove rows only if they contain zeros in the column 1 and 2. So far I've managed to remove all columns with zeros:

mk<-mk[apply(mk!=0, 1, all),]

but don't know how to restrict to only rows which have zeros in columns 1 and 2 specifically.

Expected result:

    col1 col2 col3 col4
row1   1   0     6    7
row2   5   7     0    6

Upvotes: 1

Views: 1790

Answers (1)

akrun
akrun

Reputation: 887951

We can use rowSums to create a logical vector. i.e. subset the first two columns of 'mk', check if it is equal to 0, get the rowSums of logical matrix and convert to a logical vector with < 2, use that as row index to subset the rows

mk[rowSums(mk[, 1:2] == 0) < 2,]
#     col1 col2 col3 col4
#row1    1    0    6    7
#row2    5    7    0    6

Or using apply

mk[!apply(mk[, 1:2]==0, 1, all),]
#     col1 col2 col3 col4
#row1    1    0    6    7
#row2    5    7    0    6

Or with any

mk[apply(mk[, 1:2], 1, any),]

data

mk <- structure(c(1L, 5L, 0L, 0L, 7L, 0L, 6L, 0L, 4L, 7L, 6L, 6L), 
.Dim = 3:4, .Dimnames = list(
    c("row1", "row2", "row3"),
    c("col1", "col2", "col3", "col4"
    )))

Upvotes: 2

Related Questions