Reputation: 2109
I want to rename a column in a R dataframe, and the existing column name value I want to rename is in a vector. I don't know what it will be as it's computed from user input.
I've tried this, but it no worky....
> head(iris)
Sepal.Length Sepal.Width Petal.Length Petal.Width Species
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
> myOldNameVector<-c("Petal.Width")
> head(rename(iris, myNewName = myOldNameVector))
Error: Unknown variables: myOldNameVector.
>
Anyone know what the correct incantation is? Thanks!
Upvotes: 1
Views: 275
Reputation: 787
Or use the colnames variable:
#simulate user input
userInput <- "Petal.Length"
#Load the iris dataframe
df <- iris
#find the column that matches user input and rename it
colnames(df)[colnames(df) == userInput] <- "spam"
#Show the results
head(df)
Sepal.Length Sepal.Width spam Petal.Width Species
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
Upvotes: 1
Reputation: 54267
dplyr 0.6.0 will change a few things; I think it will soon be:
library(dplyr)
packageVersion("dplyr")
# [1] ‘0.5.0.9002’
myOldNameVector<-c("Petal.Width")
head(rename(iris, myNewName = !!as.name(myOldNameVector)))
# Sepal.Length Sepal.Width Petal.Length myNewName Species
# 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
Upvotes: 2
Reputation: 2016
You can use rename_
library(dplyr)
iris %>%
rename_("New_Petal_Width" = "Petal.Width")
or
myOldNameVector <- c("Petal.Width")
iris %>%
rename_("New_Petal_Width" = myOldNameVector)
Upvotes: 1
Reputation: 14370
How about using the names()
function instead?
myOldNameVector<-c("Petal.Width", "Sepal.Width")
myNewNameVector <- c("Name1", "Name2")
names(iris)[names(iris) %in% myOldNameVector] <- myNewNameVector
head(iris)
# Sepal.Length Name1 Petal.Length Name2 Species
#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
Upvotes: 0