2

Delete rows where any column contains number

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

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

Extending on the question from the post above.

Suppose I have a dataset called m5:

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

How do I select only rows where any column contains the value 12 or 9 or 7.

The end output should be rows 1, 2, and 6.

Also would be helpful if the proposed answer works for strings as well.

Mark
  • 639
  • 1
  • 6
  • 15
  • 1
    Note that your dataframe `m6` is a random sample and you haven't given any `set.seed()` starting value. So everybody who tries your sample will get different results. – eastclintw00d Jun 28 '19 at 21:55
  • @eastclintw00d Sorry I did but I misformatted the post, here is the seed I used so should be good to go! – Mark Jun 28 '19 at 21:56

1 Answers1

1

Could try:

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

Giving:

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

There's also a dplyr possibility, but that may be an overkill:

dplyr::filter_all(m5, any_vars(. %in% c(12, 9, 7)))
arg0naut91
  • 14,574
  • 2
  • 17
  • 38