How to Rename Column Headers in R

I have two separate datasets: one has the column headers and another has the data.

The first one looks like this:

where I want to make the 2nd column as the column headers of the next dataset:

How can I do this? Thank you.

2

3 Answers

In general you can use colnames, which is a list of your column names of your dataframe or matrix. You can rename your dataframe then with:

colnames(df) <- *listofnames*

Also it is possible just to rename one name by using the [] brackets. This would rename the first column:

colnames(df2)[1] <- "name"


For your example we gonna take the values of your column. Try this:

colnames(df2) <- as.character(df1[,2])

Take care that the length of the columns and the header is identical.


Equivalent for rows is rownames()

dplyr way w/ reproducible code:

library(dplyr)
df <- tibble(x = 1:5, y = 11:15)
df_n <- tibble(x = 1:2, y = c("col1", "col2"))
names(df) <- df_n %>% select(y) %>% pull()

I think the select() %>% pull() syntax is easier to remember than list indexing. Also I used names over colnames function. When working with a dataframe, colnames simply calls the names function, so better to cut out the middleman and be more explicit that we are working with a dataframe and not a matrix. Also shorter to type.

You can simply do this :

names(data)[3]<- 'Newlabel'

Where names(data)[3] is the column you want to rename.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

James H. Sterling

James H. Sterling

Environmental Science & Climate Journalist

James Sterling reports on renewable energy developments, climate policy, ecological conservation, and green tech innovations around the globe.

Share this article
Twitter Facebook Pinterest