Renaming multiple columns with certain regex pattern? rename + across + str_extract?

Let's say there are a million columns that start with f_. Let's say there are 3
f_x
f_y
f_z

How can I rename all of them to remove f_ part of their names?

names(df) <- sub("f_", "", names(df))
2 Likes

Ah thanks, but I'm looking to use dplyr and stringr for this.

Sure, you can do that, but I really don't know why you would want to do so. The dplyr & stringr functions just translate into something like the above, but via much more convoluted syntax.

1 Like

I'm confused if from a million columns starting with f_you want to remove only the 3 begining with f_x/y/z , or get rid of all the f_ stubs throughout ?

1 Like

Throughout, sorry that wasn't clear

Here is a pipable version; rename_with can take a simple form similar to the base R solution

library(tidyverse)
set.seed(42)
(example_source <- map_dfc(c(letters,LETTERS),\(x_){
  nm <- paste0('f_',x_)
  tibble({{nm}} := sample.int(n=100,size=1))
}))

example_solve_1 <- example_source
names(example_solve_1) <- sub("f_", "", names(example_solve_1))
example_solve_1

example_solve_2 <- example_source |> 
  rename_with(.fn = \(x)sub("f_","",x))

identical(example_solve_1,
          example_solve_2)
# TRUE
2 Likes

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.