user18937485
user18937485

Reputation:

How to rename column with using paste() function in R?

Let's say I have df like this:

df <- data.frame (var1  = c(12,56,23),
                  var2 = c(12,12,34))

How can I rename the first column with paste() function?

x <- "USD"

df %>% rename(paste(x,"varNEW") = var1)

Upvotes: 1

Views: 1269

Answers (3)

Mohamed Desouky
Mohamed Desouky

Reputation: 4425

In Base R

x <- "USD"
names(df)[1] <- paste(x , "varNew")

If you want to rename other columns

x <- c("USD1" , "USD2")
names(df) <- paste(x , "varNew")

Upvotes: 0

stefan
stefan

Reputation: 123903

Using setNames you could do:

library(dplyr)

df %>% 
  rename(setNames("var1", paste(x, "varNEW", sep = "_")))
#>   USD_varNEW var2
#> 1         12   12
#> 2         56   12
#> 3         23   34

or using the special assignment operator :=:

df %>% 
  rename("{x}_varNEW" := var1)
#>   USD_varNEW var2
#> 1         12   12
#> 2         56   12
#> 3         23   34

Upvotes: 2

MonJeanJean
MonJeanJean

Reputation: 2906

You can use rename_with function:

x <- "USD"

df %>%
  rename_with(~paste(x,"varNEW"),
              .cols = var1)

Output:

  USD varNEW var2
1         12   12
2         56   12
3         23   34

Upvotes: 1

Related Questions