Change the name of a variable in an R dataframe

6

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

    
asked by anonymous 11.09.2018 / 22:53

4 answers

5

Using grep to find the number of the column 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
    
11.09.2018 / 23:46
4

With dplyr you can do this:

library(dplyr)
df <- df %>% rename(Pais = Country)
    
11.09.2018 / 23:16
3

Another way, but without using packages.

x = names(dataset)
x[(names(dataset) == "Country")] = "Pais"
colnames(dataset) = x
    
11.09.2018 / 23:39
2

You can also do this:

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