Search code examples
rdplyrrename

Rename all columns except id column by adding a prefix using dplyr


I have a dataframe with columns id, feature_1, feature_2, feature_3 as follows.

df = data.frame(
  id = sample(letters, 5),
  feature_1 = sample(1:10, 5),
  feature_2 = runif(5),
  feature_3 = rnorm(5)
)

I want to rename all the feature columns by adding a prefix. The following line doesn't work and output error.

df %>%
  rename_with(~(ifelse(names(.x) == "id", paste0("source_", names(.x)), "id")))

Error in names[cols] <- .fn(names[cols], ...) : 
  replacement has length zero

Any hint on how to modify this? What does .x represent inside rename_with? Thanks in advance!


Solution

  • library(dplyr)
    
    df %>% 
      rename_with(~ paste0("source_", .), -id)
    

    The third argument to rename_with is .cols, where you can use tidyselect syntax to select the columns. Here -id excludes this column.


    Per the comments the . syntax is a cleaner/simpler style than an writing an anonymous function, but you could accomplish this equivalently as:

    df %>% 
      rename_with(function(x) paste0("source_", x), -id)
    
    # R >= 4.1.0
    df %>% 
      rename_with(\(x) paste0("source_", x), -id)