dplyr remove prefix column names in r

To remove prefix column names in R using dplyr package, you can use the rename_with function with str_remove function from stringr package.

main.r
library(dplyr)
library(stringr)

df <- df %>%
  rename_with(~str_remove(., "^prefix_"), starts_with("prefix_"))
112 chars
6 lines

In this code, df is the data frame where you want to remove the prefix from column names. rename_with function allows renaming column names based on a condition that is specified with starts_with function. starts_with function selects all column names that start with a specified string. The ~str_remove(., "^prefix_") is a lambda function that removes the prefix "prefix_" from each selected column name using str_remove function from stringr package.

Please note that this code assumes that all column names that need to be changed start with the prefix "prefix_" and do not have any other underscore characters in their names. Also, make sure to load the necessary packages before running the code.

gistlibby LogSnag