Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

find names/text that end with certain pattern (using BASE R)

I’m trying to find all variables names that end with "DE".

I’m already using this "grep" to find variables that start with "TR"

names(df )[ grep( "^(TR)" ,  names(df) ) ]

Is there a grep way to find the end pattern.
Just an fyi, I know I can do it with "ends_with" but I’m trying to find a base r method.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

names( df %>% select(ends_with( "DE" ) ) )  

Thanks.

>Solution :

There is already endsWith in base R

names(df)[endsWith(names(df), "DE")]

-a reproducible example

> names(iris)[endsWith(names(iris), "Length")]
[1] "Sepal.Length" "Petal.Length"

Or with grep use the $ to specify the end of the string (also, with grep, we can use value = TRUE which returns the names instead of the numeric index

grep("DE$", names(df), value = TRUE)
# similar to
names(df)[grep("DE$", names(df)]

Or in a base R pipe

grep("DE$", names(df)) |>
   `[`(names(df), i = _)
grep("Length", names(iris)) |> 
  `[`(names(iris), i = _)
[1] "Sepal.Length" "Petal.Length"
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading