Reputation: 1186
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
Upvotes: 28
Views: 16471
Reputation: 966
Much simpler: you can rename a column just by using numbers. This works:
df <- df %>%
rename(newNameForFirstColumn = 1, newNameForSecondColumn = 2)
Upvotes: 61
Reputation: 346
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.
Upvotes: 20