Hello,
I am trying to rename a variable inside a data frame with a name that is store in an R object as so :
iris1 <- iris # the df with the variable that I want to change the name
New_name <- "my nicer name"
iris1 <- rename(iris1, New_name = Species)
But this code doesn't work and the variable is simply rename as "New_name"
...
How can I do this ?
Thanks,
You can use:
library(dplyr) |> suppressPackageStartupMessages()
iris1 <- iris # the df with the variable that I want to change the name
New_name <- "my nicer name"
iris1 <- rename(iris1, {{New_name}} := Species)
head(iris1)
#> Sepal.Length Sepal.Width Petal.Length Petal.Width my nicer name
#> 1 5.1 3.5 1.4 0.2 setosa
#> 2 4.9 3.0 1.4 0.2 setosa
#> 3 4.7 3.2 1.3 0.2 setosa
#> 4 4.6 3.1 1.5 0.2 setosa
#> 5 5.0 3.6 1.4 0.2 setosa
#> 6 5.4 3.9 1.7 0.4 setosa
Created on 2023-08-18 with reprex v2.0.2
This is explained in more details here.
1 Like
With base code you could make this:
iris1 <- iris
New_name <- "my nicer name"
names(iris1)[5] <- New_name # 5 is the position of column for change the name
head(iris1)
# Sepal.Length Sepal.Width Petal.Length Petal.Width my nicer name
#1 5.1 3.5 1.4 0.2 setosa
#2 4.9 3.0 1.4 0.2 setosa
#3 4.7 3.2 1.3 0.2 setosa
#4 4.6 3.1 1.5 0.2 setosa
#5 5.0 3.6 1.4 0.2 setosa
#6 5.4 3.9 1.7 0.4 setosa
3 Likes
system
Closed
4
This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.
If you have a query related to it or one of the replies, start a new topic and refer back with a link.