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)
CodePudding user response:
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
CodePudding user response:
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
CodePudding user response:
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")