Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R: dplyr - Rename column name by position instead of name

Tags:

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 
like image 417
vikas Avatar asked Apr 12 '15 05:04

vikas


People also ask

How do I rename a column in R based on position?

How to rename column by index in the R data frame? R provides base function colnames() and names() function to change column name by index position. Besides these, use dplyr rename() , select() and rename_with() to rename/change a DataFrame (data. frame) column.

How do I change the column name in R dplyr?

To rename a column in R you can use the rename() function from dplyr. For example, if you want to rename the column “A” to “B”, again, you can run the following code: rename(dataframe, B = A) .

How do I rename a specific column in R?

colnames() method in R is used to rename and replace the column names of the data frame in R. The columns of the data frame can be renamed by specifying the new column names as a vector. The new name replaces the corresponding old name of the column in the data frame.

How do I rename multiple columns in R?

rename() is the method available in the dplyr library which is used to change the multiple columns (column names) by name in the dataframe. The operator – %>% is used to load the renamed column names to the dataframe. At a time it will change single or multiple column names.


1 Answers

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

df <- df %>%          rename(newNameForFirstColumn = 1, newNameForSecondColumn = 2) 
like image 63
Max Shron Avatar answered Oct 10 '22 20:10

Max Shron