How to use both start_with and ends_with parameters at the same time in the same select clause?

I want to 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 crack it with the following snippet

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

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

+5
source share
2 answers

Instead of matches you can use a regex:

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

must do the job.

Example of fictitious use with iris :

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

you can use this:

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

added the same example as @Vincent Bonhomme:

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

Source: https://habr.com/ru/post/1260451/


All Articles