【问题标题】:Delete All Rows With Any of N Variables [duplicate]删除具有任何 N 个变量的所有行 [重复]
【发布时间】:2019-11-10 19:14:03
【问题描述】:

Delete rows where any column contains number

Finding rows containing a value (or values) in any column

在任何列中查找包含一个(或多个值)的行

从上面的帖子中扩展问题。

假设我有一个名为 m5 的数据集:

set.seed(1234)
m3 <- matrix(12:1,nrow=6,ncol=4)
m4<-as.data.frame(m3)
m5 <- m4[sample(nrow(m4)),]

如何仅选择任何列包含值 12 或 9 或 7 的行。

最终输出应该是第 1、2 和 6 行。

如果建议的答案也适用于字符串,也会很有帮助。

【问题讨论】:

  • 请注意,您的数据框 m6 是一个随机样本,您没有给出任何 set.seed() 起始值。所以每个尝试你的样本的人都会得到不同的结果。
  • @eastclintw00d 抱歉,我写错了帖子的格式,这是我使用的种子,应该可以继续使用!

标签: r dataframe data-manipulation data-management


【解决方案1】:

可以试试:

m5[apply(m5, 1, function(x) any(x %in% c(12, 9, 7))), ]

给予:

  V1 V2 V3 V4
4  9  3  9  3
1 12  6 12  6
6  7  1  7  1

也有dplyr 的可能性,但这可能有点矫枉过正:

dplyr::filter_all(m5, any_vars(. %in% c(12, 9, 7)))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-01
    • 2019-11-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多