Garp Garp - 9 days ago 7
R Question

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

Answer

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"