简体   繁体   中英

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

We can use rowSums to create a logical vector. ie 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"
    )))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM