dplyr rename prefix column names in r

To rename column names in a data frame in R using dplyr, we can use the rename_with() function along with the starts_with() function to target specific column names based on a prefix. Here's an example:

main.r
library(dplyr)

# create sample data frame
df <- data.frame(id = 1:5, var1_a = runif(5), var1_b = runif(5), var2_a = runif(5), var2_b = runif(5))

# use rename_with() to add "new_" prefix to var1 and var2 columns
df_renamed <- df %>%
  rename_with(~paste0("new_",.), starts_with("var1"), starts_with("var2"))

# view renamed data frame
df_renamed
347 chars
12 lines

In this example, we first created a sample data frame called df. Next, we used rename_with() to add a prefix of "new_" to any columns that start with "var1" or "var2". The ~paste0("new_", .) syntax is what adds the prefix to the selected column names. We then assigned the result to df_renamed and printed the resulting data frame.

The resulting output should look like this:

main.r
  id    new_var1_a new_var1_b new_var2_a new_var2_b
1  1 0.0812526957  0.3774876  0.7807511  0.1371220
2  2 0.6760087902  0.1708335  0.6899029  0.7412111
3  3 0.9450726877  0.4146930  0.5743925  0.7032092
4  4 0.0124553741  0.1447098  0.1947084  0.1924753
5  5 0.4248646400  0.8198908  0.7824500  0.6886603
307 chars
7 lines

Here, we can see that the original column names starting with "var1" and "var2" have been renamed with the "new_" prefix using dplyr.

gistlibby LogSnag