Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 502
Garp Avatar asked Nov 28 '16 12:11

Garp


2 Answers

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"
like image 183
cccmir Avatar answered Sep 27 '22 16:09

cccmir


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"
like image 29
Vincent Bonhomme Avatar answered Sep 27 '22 16:09

Vincent Bonhomme