Here are multiple ways how to rename columns in R.
Here is a data frame that I used in multiple situations that shows how to change data frame column names.
df <- data.frame( Values1 = sample(1:10, 5, replace=T), Values2 = sample(1:10, 5, replace=T), Values3 = sample(1:10, 5, replace=T) )
Rename R data frame column by location
By using names or colnames functions, you can see the column index number and use that to rename the necessary one.
#change name of the first column names(df)[1] <- 'NewName'
It is fast and simple, but be aware – if the column changes position that might lead to error.
Rename R data frame column by name
Here is the simplest method.
names(df)[names(df) == 'Values1'] <- 'NewName'
Of course, there are plenty of other ways that if there is a function that can confirm the match. Like grepl or match functions.
names(df)[match(names(df), 'Values1')] <- 'NewName'
Rename multiple R data frame columns at the same time
First of all, you should create a set of column names for all of the data frame columns and then do the replacement.
NewNames <- c('NewName1', 'NewName2', 'NewName3') names(df) <- NewNames
Be aware if column changes position that might lead to error.
Rename R data frame columns with dplyr
You just have to point out the new column name and the old. One of the advantages is that if you press Tab inside rename function, you can get a necessary column name and avoid typos.
require(dplyr) #rename only one column df <- df %>% rename(NewName = Values1) #rename all columns df <- df %>% rename(NewName = Values1, NewName2 = Values2, NewName3 = Values3)
If you want to know other useful RStudio tips and tricks, take a look at this post.