删除所有具有N个变量的所有行

时间:2019-06-28 21:51:37

标签: r dataframe data-manipulation data-management

Delete rows where any column contains number

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

假设我有一个名为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行。

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

1 个答案:

答案 0 :(得分: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)))
相关问题