[英]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:我只需要删除第 1 列和第 2 列中包含零的行。到目前为止,我已经设法删除了所有包含零的列:
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.但不知道如何专门限制为仅在第 1 列和第 2 列中具有零的行。
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.我们可以使用
rowSums
创建逻辑向量。 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'的前两列,检查它是否等于0,获取逻辑矩阵的
rowSums
并转换为<
2的逻辑向量,将其用作行索引以对行进行子集化
mk[rowSums(mk[, 1:2] == 0) < 2,]
# col1 col2 col3 col4
#row1 1 0 6 7
#row2 5 7 0 6
Or using apply
或者使用
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
或者与
any
mk[apply(mk[, 1:2], 1, any),]
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"
)))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.