【问题标题】:R - Subset rows of a data frame on a condition in all the columnsR - 在所有列中的条件下,数据框的子集行
【发布时间】:2016-11-08 16:07:51
【问题描述】:

我想在所有列中的单个条件下对数据框的行进行子集化,避免使用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

谢谢

【问题讨论】:

  • 请进一步详细说明您的问题。例如,子集条件是什么?
  • @TimBiegeleisen 另一种可能的模式是删除所有包含 0 的行。
  • 一个apply函数可以帮助mydf [ !apply(mydf, 1, function(x) any(x == 0)), ]
  • 试试df[!rowSums(df == 0),]
  • @StevenBeaupré 打高尔夫球? df[!rowSums(!df),] :)

标签: r dataframe subset


【解决方案1】:
# 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,]

【讨论】:

    【解决方案2】:

    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))]),]
    

    【讨论】:

      猜你喜欢
      • 2021-10-03
      • 2014-02-20
      • 1970-01-01
      • 2020-12-25
      • 1970-01-01
      • 2023-01-25
      • 1970-01-01
      • 1970-01-01
      • 2021-06-05
      相关资源
      最近更新 更多