【问题标题】:How to remove rows where columns satisfy certain condition in data frame如何删除数据框中列满足特定条件的行
【发布时间】:2013-03-23 04:24:03
【问题描述】:

我有一个看起来像这样的数据框

df <- data.frame(cbind(1:10, sample(c(1:5), 10, replace=TRUE)))
# in real case the columns could be more than two
# and the column name could be anything.

我想要做的是删除所有列的值所在的所有行 小于 5。 有什么办法呢?

【问题讨论】:

    标签: r dataframe


    【解决方案1】:

    首先...请停止使用cbind 创建data.frames。如果你继续,你会后悔的。 R会惩罚你。

    df[ !rowSums(df <5) == length(df), ]
    

    (length() 函数返回数据框中的列数。)

    【讨论】:

    • +1 表示cbind 建议。我认为它实际上是!=。他想删除那些行,而不是保留它们。
    • 不是,我猜它也可能是!=。固定
    • (A!=B)!(A==B)不一样吗? :-)
    • 我一开始以为是NO,后来又反过来了。
    【解决方案2】:
    df[!apply(df,1,function(x)all(x<5)),]
    

    【讨论】:

    • 谢谢,但是您的方法删除了所有 at least one 列小于 5 的列。在我的 OP 中,all columns 需要满足该条件。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多