Economist_Ayahuasca
Economist_Ayahuasca

Reputation: 1642

Selecting values in columns using grep

I have the following dataframe:

df = 
name1 name2 Value
Dii   Rif   8
Dif   Dib   5
Fih   Qiv   6

I would like to select the row with the following combination:

combination = 'if|ii'

In other words, to select those values of the columns name1 and name2 that have any of the members of the vector combination. Remember that they must both values be in there. In this case ONLY the first row should be selected.

this is what I have tried:

df <- df %>%
   select(grep(combination, c('name1', 'name2')))

But I get an empty df.

Upvotes: 0

Views: 155

Answers (1)

Joris C.
Joris C.

Reputation: 6234

Using dplyr, I think you want to use filter instead of select, one way to go would be:

library(dplyr)

combination <- "if|ii"

df %>%
  filter(grepl(combination, name1), grepl(combination, name2))
#> # A tibble: 1 x 3
#>   name1 name2 Value
#>   <chr> <chr> <dbl>
#> 1 Dii   Rif       8

Upvotes: 1

Related Questions