1

Stupid question probably, I'm very new to R.

mtcars2 <- filter(mtcars, contains(integer_vector, mtcars$hp))

I want to filter mtcars by only saving the rows where the value of hp is in the integer_vector. With this code, I get:

Error in contains(integer_vector, mtcars2$hp) : 
  is_string(match) is not TRUE

Why is that?

2 Answers2

3

contains is a select helper function for selecting columns. And it works on substrings, i.e., "bananas" contains "a".

You want %in%. Also, don't use data$ inside dplyrcommands. They take a data argument so that you don't have to keep typing data$ -- it will cause bugs.

mtcars2 <- filter(mtcars, hp %in% integer_vector)
Gregor Thomas
  • 136,190
  • 20
  • 167
  • 294
0

Here is a similar row filtering exercise using data.table:

require(data.table)

# Example data.table
dt = data.table(
  hp = c(200, 400, 600, 200),
  id = c('A', 'B', 'C', 'D')
)

# Which hps do we want?
hp_restr = c(200, 400)

# Creating a filtered data.table using restriction on hp
dt_filt = dt[hp %in% hp_restr] 

Original Data

> dt
    hp id
1: 200  A
2: 400  B
3: 600  C
4: 200  D

Filtered Data

> dt_filt
    hp id
1: 200  A
2: 400  B
3: 200  D
JDG
  • 1,342
  • 8
  • 18