Search code examples
rtidyverse

Adding a suffix to a selection of column names in tidyverse


This great post showed me how to add prefixes to column names using dplyr. But what if I only want to add prefixes to some of those column

library(dplyr)

(df <- data.frame(x = c(1, 2), y = c(3, 4), z = c(5, 6)))

#   x y z
# 1 1 3 5
# 2 2 4 6

Now if I want to add a prefix to all of these I can do this.

## Adding prefixes
df %>% rename_with( ~ paste0("a", .x))

#   ax ay az
# 1  1  3  5
# 2  2  4  6

But what if I only wanted to add a prefix to columns x and y? Some sort of select syntax? I tried

df %>% rename_with(across(cols = c("x", "y")),
                   ~ paste0("a", .x))

But got an error saying across() could only be used inside dplyr verbs, and I guess rename_with isn't one of those


Solution

  • You may select columns in rename_with -

    library(dplyr)
    
    df %>% rename_with(~paste0("a", .x), c(x, y))
    
    #  ax ay z
    #1  1  3 5
    #2  2  4 6