简体   繁体   中英

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

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"

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM