Garp
Garp

Reputation: 419

How to use both starts_with and ends_with at the same time in one select statement?

I want select all columns starting with fy and ending with giving using dplyr. I tried the following code

df %>% select(start_with('fy') & ends_with('giving')

but it didn't work.

p/s: actually I can hack it with the following chunk

df %>% select(starts_with('fy')) %>% select(ends_with('giving'))

But I still want to put all the two conditions in one place

Upvotes: 21

Views: 5290

Answers (3)

user63230
user63230

Reputation: 4698

This works too (extract variables starting with Pe and ending in Length):

iris %>% 
  select_at(vars(starts_with("Pe") & ends_with("Length")))
#     Petal.Length
# 1            1.4
# 2            1.4
# 3            1.3
# 4            1.5

Upvotes: 0

cccmir
cccmir

Reputation: 1003

you can use this:

df %>% select(intersect(starts_with('fy') , ends_with('giving')))

added same example as @Vincent Bonhomme:

iris %>% select(intersect(starts_with("Pet"), ends_with("gth"))) %>% colnames
#[1] "Petal.Length"

Upvotes: 21

Vincent Bonhomme
Vincent Bonhomme

Reputation: 7453

You can try using matches instead with a regular expression:

 df %>% select(matches("^fy.*giving$"))

should do the job.

A dummy example using iris:

iris %>% select(matches("^Pet.*gth$")) %>% colnames
[1] "Petal.Length"

Upvotes: 11

Related Questions