user4394417
user4394417

Reputation:

R - dplyr rename colname by variable

my dataframe looks like this

df <-
  data.frame(
    date = c("2020-01-01", "2020-02-01"),
    id = c(1, 2),
    sold = c(100, 200),
    country = c("us", "eu")
  )

I'd like to rename date, id and sold columns by pasting my var value and actual colname so result would be

var = "rename_to"

result <-
  df <-
  data.frame(
    rename_to_date = c("2020-01-01", "2020-02-01"),
    rename_to_id = c(1, 2),
    rename_to_sold = c(100, 200),
    country = c("us", "eu")
  )

Please I'm looking for some dplyr solution.

Upvotes: 0

Views: 95

Answers (2)

akrun
akrun

Reputation: 886948

Using base R

names(df)[1:3] <- paste0(var, "_", names(df)[1:3])

Upvotes: 0

Ronak Shah
Ronak Shah

Reputation: 388817

You can use rename_with :

library(dplyr)
df %>% rename_with(~paste(var, ., sep = '_'), .cols = c(date, id, sold))

#  rename_to_date rename_to_id rename_to_sold country
#1     2020-01-01            1            100      us
#2     2020-02-01            2            200      eu

Upvotes: 1

Related Questions