remove character for all column names in a data frame

Viewed 346

I have a large dataframe. I'm trying to remove v character from variable names of a data frame

df <- tibble(q_ve5 = 1:2,
                 q_f_1v = 3:4,
                 q_vf_2 = 3:4,
                 q_e6 = 5:6,
                 q_ev8 = 5:6)

I tried this. It seems my regular expression pattern is not correct

df %>% 
  rename_all(~ str_remove(., "\\v\\d+$"))

My desired col names:

q_e5 q_f_1 q_f_2  q_e6 q_e8
1 Answers

If we need to remove only 'v' the one of more digits (\\d+) at the end ($) is not needed as the expected output also removes 'v' from first column 'q_ve5'

library(dplyr)
library(stringr)
df %>% 
    rename_with(~ str_remove(., "v"), everything())

-output

# A tibble: 2 × 5
   q_e5 q_f_1 q_f_2  q_e6  q_e8
  <int> <int> <int> <int> <int>
1     1     3     3     5     5
2     2     4     4     6     6

Or without any packages

names(df) <- sub("v", "", names(df))
Related