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.

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"

Leave a Reply