Changing the name of a variable in a dataframe R

Asked

Viewed 7,118 times

6

I have a dataframe with 34846 observations and 15 variables, I would like to know how to change the name of a variable. Example: I have the variable "Country" and I would like to rename it "Country"

4 answers

5

With dplyr you can do so:

library(dplyr)
df <- df %>% rename(Pais = Country)
  • 2

    Or with a shorter syntax, since you’re using Pipes: df %<>% rename(Pais = Country)

5

Using grep to find the column number you want to rename:

dados <- data.frame(
  'Year' = 2015:2018,
  'Country' = 'Brazil',
  'Continent' = 'America'
)

names(dados)[grep('Country', names(dados))] <- 'País'

> dados
  Year   País Continent
1 2015 Brazil   America
2 2016 Brazil   America
3 2017 Brazil   America
4 2018 Brazil   America

3

Another way, but without using packages.

x = names(dataset)
x[(names(dataset) == "Country")] = "Pais"
colnames(dataset) = x

2

You can do that too:

colnames(dados)[1]<-'Pais' # 1 é o número da coluna Country

Browser other questions tagged

You are not signed in. Login or sign up in order to post.