The Wayback Machine - https://web.archive.org/web/20240815120041/https://www.geeksforgeeks.org/change-column-name-of-a-given-dataframe-in-r/
Open In App

Change column name of a given DataFrame in R

Last Updated : 16 Mar, 2021
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

A data frame is a tabular structure with fixed dimensions, of each rows as well as columns. It is a two-dimensional array like object with numerical, character based or factor-type data. Each element belonging to the data frame is indexed by a unique combination of the row and column number respectively. Column names are addressed by unique names.

Method 1: using colnames() method

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. The length of new column vector should be equivalent to the number of columns originally. Changes are made to the original data frame. 

Syntax:

colnames(df) <- c(new_col1_name,new_col2_name,new_col3_name)

Example:

R




# declaring the columns of data frame
df = data.frame(
col1 = c('A', 'B', 'C', 'J', 'E', NA,'M'),
col2 = c(12.5, 9, 16.5, NA, 9, 20, 14.5),
col3 = c(NA, 3, 2, NA, 1, NA, 0))
  
# printing original data frame
print("Original data frame : ")
print(df)
  
print("Renaming columns names ")
  
# assigning new names to the columns of the data frame
colnames(df) <- c('C1','C2','C3')
  
# printing new data frame
print("New data frame : ")
print(df)


Output:

[1] “Original data frame : “

 col1 col2 col3

1    A 12.5   NA

2    B  9.0    3

3    C 16.5    2

4    J   NA   NA

5    E  9.0    1

6 <NA> 20.0   NA

7    M 14.5    0

[1] “Renaming columns names “

[1] “New data frame : “

   C1   C2 C3

1    A 12.5 NA

2    B  9.0  3

3    C 16.5  2

4    J   NA NA

5    E  9.0  1

6 <NA> 20.0 NA

7    M 14.5  0

1(A) .Specific columns of the data frame can also be renamed using the position index of the respective column. 

Syntax:

colnames(df)[col_indx] <- “new_col_name_at_col_indx”

Approach

  • Create dataframe
  • Select the column to be renamed by index
  • Provide a suitable name
  • Change using colnames() function

Example:

R




# declaring the columns of data frame
df = data.frame(
col1 = c('A', 'B', 'C', 'J', 'E', NA,'M'),
col2 = c(12.5, 9, 16.5, NA, 9, 20, 14.5),
col3 = c(NA, 3, 2, NA, 1, NA, 0))
  
# printing original data frame
print("Original data frame : ")
print(df)
  
print("Renaming columns names ")
  
# assigning the second column name to a new name
colnames(df)[2] <- "new_col2"
  
# printing new data frame
print("New data frame : ")
print(df)


Output:

[1] “Original data frame : “

 col1 col2 col3

1    A 12.5   NA

2    B  9.0    3

3    C 16.5    2

4    J   NA   NA

5    E  9.0    1

6 <NA> 20.0   NA

7    M 14.5    0

[1] “Renaming columns names “

[1] “New data frame : “

 col1 new_col2 col3

1    A     12.5   NA

2    B      9.0    3

3    C     16.5    2

4    J       NA   NA

5    E      9.0    1

6 <NA>     20.0   NA

7    M     14.5    0

1(B). Column names can also be replaced by using the which(names(df)) function, which searches for the column with the specified old name and then replaces it with the new specified name instance. 

Syntax:

colnames(dataframe)[which(names(dataframe) == “oldColName”)] <- “newColName”

Approach

  • Create data frame
  • Select name of the columns to be changed
  • Provide a suitable name
  • Use the function

Example:

R




# declaring the columns of data frame
df = data.frame(
col1 = c('A', 'B', 'C', NA,'M'),
col2 = c(12.5, 9, 16.5,  20, 14.5),
col3 = c(NA, 3, 2, NA, 0))
  
# printing original data frame
print("Original data frame : ")
print(df)
  
print("Renaming columns names ")
# assigning the second column name to a new name
  
colnames(df)[2] <- "new_col2"
  
# printing new data frame
print("After changing the data frame col2 name : ")
print(df)
  
# replacing first column name
colnames(df)[which(names(df) == "col1")] <- "new_col1"
  
# printing new data frame
print("After changing the data frame col1 name : ")
print(df)


Output

[1] “Original data frame : “

 col1 col2 col3

1    A 12.5   NA

2    B  9.0    3

3    C 16.5    2

4 <NA> 20.0   NA

5    M 14.5    0

[1] “Renaming columns names “

[1] “After changing the data frame col2 name : “

 col1 new_col2 col3

1    A     12.5   NA

2    B      9.0    3

3    C     16.5    2

4 <NA>     20.0   NA

5    M     14.5    0

[1] “After changing the data frame col1 name : “

 new_col1 new_col2 col3

1        A     12.5   NA

2        B      9.0    3

3        C     16.5    2

4     <NA>     20.0   NA

5        M     14.5    0

Method 2: using setNames() method

setNames() method in R can also be used to assign new names to the columns contained within a list, vector or tuple. The changes have to be saved back then to the original data frame, because they are not retained.

Syntax:

setnames(df, c(names of new columns))

Approach

  • Create data frame
  • Rename column using function
  • Display modified data frame

Example:

R




# declaring the columns of data frame
df = data.frame(
col1 = c('A', 'B', 'C', NA,'M'),
col2 = c(12.5, 9, 16.5,  20, 14.5),
col3 = c(NA, 3, 2, NA, 0))
  
# printing original data frame
print("Original data frame : ")
print(df)
  
# print("Renaming columns names ")
# renaming all the column names of data frame
df <- setNames(df, c("changed_Col1","changed_Col2","changed_Col3"))
  
print("Renamed data frame : ")
print(df)


Output

[1] “Original data frame : “

  col1 col2 col3

1    A 12.5   NA

2    B  9.0    3

3    C 16.5    2

4 <NA> 20.0   NA

5    M 14.5    0

[1] “Renamed data frame : “

  changed_Col1 changed_Col2 changed_Col3

1            A         12.5           NA

2            B          9.0            3

3            C         16.5            2

4         <NA>         20.0           NA

5            M         14.5            0



Similar Reads

Change more than one column name of a given DataFrame in R
A data frame is a tabular structure with fixed dimensions, of each row as well as columns. It is a two-dimensional array-like object with numerical, character-based, or factor-type data. Each element belonging to the data frame is indexed by a unique combination of the row and column number respectively. Column names are addressed by unique names.
4 min read
Coercing the Argument to a Name in R Programming - as.name() Function
as.name() function in R Language is used to coerce the argument to a name. The as.name() and as.symbol() functions are identical. Syntax: as.name(x) Parameters: x: Object to be coerced Example 1: # R program to illustrate # as.name() function # Calling the as.name() function to # coerce the argument to a name x &lt;- as.name(&quot;sample&quot;) # C
1 min read
Check if the Argument is a Name in R Programming - is.name() Function
is.name() function in R Language is used to return TRUE if the argument is name else returns FALSE. The is.name() and is.symbol() functions are identical. Syntax: is.name(x) Parameters: x: R object to be tested Example 1: # R program to illustrate # is.name() function # Initializing a string x &lt;- &quot;sample&quot; # Calling the is.name() functi
1 min read
How to Remove a Column by name and index using Dplyr Package in R
In this article, we are going to remove columns by name and index in the R programming language using dplyr package. Dataset in use: Remove a column by using column name We can remove a column with select() method by its column name. Syntax: select(dataframe,-column_name) Where, dataframe is the input dataframe and column_name is the name of the co
2 min read
Rename the column name in R using Dplyr
In this article, we are going to rename the column name using dplyr package in the R programming language. Dataset in use: Method 1: Using rename() This method is used to rename the columns in the dataframe Syntax: rename(dataframe,new_columnname=old_column,.............,name,new_columnname=old_columnname) Where dataframe is the input dataframe, ne
3 min read
Get Column Index in Data Frame by Variable Name in R
R is an open-source programming language that is used as a statistical software and data analysis tool. In R Programming Language we can work on specific columns based on their names. In this article, we will learn different methods to extract the Get Column Index in Data Frame by Variable Name in R Extract Column Index of Variable with Exact Match
5 min read
How to Name the Column When Using value_counts Function in Pandas?
In Pandas, when using the value_counts function, it's important to name the resulting column for clear data interpretation. This process involves using Pandas' functionality to assign meaningful names to the frequency count column, ensuring easier analysis and understanding of the data. In this article, we will explore three different methods/appro
6 min read
How Do You Delete a Column by Name in data.table in R?
Data manipulation is a critical aspect of the data analysis and R's data.table package is a powerful tool for handling large datasets efficiently. One common task is deleting a column by its name. This article will guide us through the process providing examples and best practices to ensure we can manage the data tables effectively. What is a data.
3 min read
What is the Difference Between Indicator Column and Categorical Identity Column in TensorFlow
Answer: In TensorFlow, an indicator column represents categorical variables as one-hot encoded vectors, while a categorical identity column represents categorical variables as integers without one-hot encoding.In TensorFlow, when working with categorical variables, you often need to convert them into a format suitable for training machine learning
3 min read
How to standardized a column of R DataFrame ?
A large dataset that had multiple columns with varying ranges and units may need to be standardized before further processing. In this article, we will be discussing how to standardize a column of dataframe in R Programming Language. Let's first discuss standardization. Standardization is a feature scaling technique. It is the process of rescaling
3 min read
three90RightbarBannerImg