2017-04-20 76 views
1

我想重命名R数据框中的列,并且我想要重命名的现有列名称值位于向量中。我不知道它会是什么,因为它是从用户输入计算出来的。如何使用向量重命名R数据框中的列以指示OLD列名称?

我已经试过这一点,但它没有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. 
> 

任何人都知道正确的咒语是什么?谢谢!

回答

1

或者使用colnames变量:

#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 
0

如何使用names()函数代替?

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 
+0

我不想这样做,因为我有大约46名,而我只是想改变其中一个。 – ThatDataGuy

+0

你甚至不需要矢量来做到这一点。你可以直接指定它:'%NameToChange'中的'names(iris)%,然后将'myNewNameVector'改为''NameWant'' –

1

您可以使用rename_

library(dplyr) 

iris %>% 
    rename_("New_Petal_Width" = "Petal.Width") 

myOldNameVector <- c("Petal.Width") 
iris %>% 
    rename_("New_Petal_Width" = myOldNameVector) 
2

dplyr 0.6.0change a few things;我认为它会很快:

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 
+0

非常酷,所以你需要'!!'?不只是'as.name'? – Zafar

相关问题