26

I want to know if there is a way to rename column names by position of the column, rather than changing by column name.

Below snippet shows how to change by name.

suppressPackageStartupMessages(library(dplyr))

gd_url  <- "http://tiny.cc/gapminder"
gtbl  <- gd_url %>%
  read.delim %>%
  tbl_df

gtbl  <- gtbl %>% rename(life_exp = lifeExp, 
                         gdp_percap = gdpPercap)
gtbl
vikas
  • 1,116
  • 1
  • 11
  • 12

2 Answers2

59

Much simpler: you can rename a column just by using numbers. This works:

df <- df %>% 
        rename(newNameForFirstColumn = 1, newNameForSecondColumn = 2)
Max Shron
  • 946
  • 7
  • 6
20

If you prefer to stick within the dplyr pipe-world, as of dplyr 0.7.2 it is possible to rename by position using the following nomenclature:

Using your original example:

gtbl  <- gtbl %>% rename("life_exp" = !!names(.[5]),
                         "gdp_percap" = !!names(.[6]))

Regards for dredging up an older post. I had a similar problem and viewed this question before figuring out this alternative solution.

Harney
  • 346
  • 2
  • 6