簡體   English   中英

R-在所有列中的條件下為數據框的行設置子集

[英]R - Subset rows of a data frame on a condition in all the columns

我想在所有列的單一條件下對數據框的行進行子集化,避免使用subset

我了解如何對單個列進行子集設置,但無法對所有列進行泛化(不調用所有列)。

初始數據幀:

  V1 V2 V3
1  1  8 15
2  2  0 16
3  3 10 17
4  4 11 18
5  5  0 19
6  0 13 20
7  7 14 21

在此示例中,我想對不包含零的行進行子集化。

預期產量:

  V1 V2 V3
1  1  8 15
2  3 10 17
3  4 11 18
4  7 14 21

謝謝

# create your data
a <- c(1,2,3,4,5,0,7)
b <- c(8,0,10,11,0,14,14)
c <- c(15,16,17,18,19,20,21)
data <- cbind(a, b, c)

# filter out rows where there is at least one 0
data[apply(data, 1, min) > 0,]

匹配0后使用rowSums函數的解決方案。

# creating your data
data <- data.frame(a = c(1,2,3,4,5,0,7), 
                   b = c(8,0,10,11,0,14,14), 
                   c = c(15,16,17,18,19,20,21))

# Selecting rows containing no 0.
data[which(rowSums(as.matrix(data)==0) == 0),]

其他方式

data[-unique(row(data)[grep("^0$", unlist(data))]),]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM