Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

r

rename

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!

like image 547
Salty Gold Fish Avatar asked Jan 25 '23 10:01

Salty Gold Fish


1 Answers

library(dplyr)

df %>% 
  dplyr::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 %>% 
  dplyr::rename_with(function(x) paste0("source_", x), -id)
like image 73
LMc Avatar answered Feb 16 '23 01:02

LMc