How to change the name of columns in R?

How to change the name of columns in R?


Let’s upload one data to R.

install.packages ("readr")
library(readr)

github= read_csv("https://raw.githubusercontent.com/agronomy4future/raw_data_practice/main/grains.csv")

dataA=github%>%data.frame
dataA

Now, I’d like to change the name of column as

field → location
genotype → variety
block → reps
treatment → experiment
shoot → branch
grain_number → GN
grain_weight → GW

I introduce two ways to change column names.


1) using colnames()

colnames(dataA)[1]<- c("location")
colnames(dataA)[2]<- c("variety")
colnames(dataA)[3]<- c("reps")
colnames(dataA)[4]<- c("anthesis")
colnames(dataA)[5]<- c("experiment")
colnames(dataA)[6]<- c("branch")
colnames(dataA)[7]<- c("GN")
colnames(dataA)[8]<- c("GW")
dataA


2) using rename() in dplyr package

In this time, I’ll use dplyr package.

install.packages ("dplyr")
library(dplyr)

dataB<-dataA %>% rename(location = 'field',
                        variety = 'genotype',
                        rep = 'block',
                        antheis = 'stage',
                        experiment = 'treatment',
                        branch = 'shoot',
                        GN = 'grain_number',
                        AGW = 'grain_weight')
dataB

Comments are closed.