R Program to Rename Columns in a Dataframe

1. Introduction

Often when working with data frames in R, we may need to rename columns for clarity, and consistency, or to avoid column name conflicts. There are multiple ways to achieve this, but one of the most straightforward methods is using the dplyr package.

2. Program Overview

1. Create a sample dataframe.

2. Use the rename() function from the dplyr package to rename specific columns.

3. Code Program

# Loading necessary library
library(dplyr)

# Create a sample dataframe
df <- data.frame(
  FirstName = c('Alice', 'Bob', 'Charlie'),
  LastName = c('Anderson', 'Brown', 'Clark'),
  Age = c(25, 30, 22)
)

# Print the original dataframe
print("Original Dataframe:")
print(df)

# Rename columns using dplyr's rename() function
df_renamed <- df %>%
  rename(
    First_Name = FirstName,
    Last_Name = LastName
  )

# Print the renamed dataframe
print("Renamed Dataframe:")
print(df_renamed)

Output:

[1] "Original Dataframe:"
  FirstName LastName Age
1     Alice Anderson  25
2       Bob    Brown  30
3   Charlie    Clark  22

[1] "Renamed Dataframe:"
  First_Name Last_Name Age
1      Alice  Anderson  25
2        Bob     Brown  30
3    Charlie     Clark  22

4. Step By Step Explanation

- We begin by loading the dplyr package, a part of the tidyverse suite of packages, which provides a variety of functions to manipulate data frames.

- A sample dataframe df is created with columns FirstName, LastName, and Age.

- The rename() function from the dplyr package is used to rename columns. In this function, the new name is provided on the left-hand side of the = sign, and the old name is provided on the right-hand side.

- After renaming, both the original and the renamed data frames are printed to see the changes.

Comments