R Program to Add Columns to a Dataframe

📘 Premium Read: Access my best content on Medium member-only articles — deep dives into Java, Spring Boot, Microservices, backend architecture, interview preparation, career advice, and industry-standard best practices.

🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.

▶️ Subscribe to My YouTube Channel (176K+ subscribers): Java Guides on YouTube

▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube

1. Introduction

Often while working with datasets in R, there's a need to add new columns based on the existing data or external information. R provides multiple ways to achieve this. Here, we will demonstrate one of the simplest methods.

2. Program Overview

1. Create an initial dataframe.

2. Add new columns to the dataframe.

3. Code Program

# Load necessary libraries
library(dplyr)

# Create an initial dataframe
df <- data.frame(
  Name = c('Alice', 'Bob', 'Charlie'),
  Age = c(25, 30, 28)
)

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

# Add a new column 'Occupation' to the dataframe
df$Occupation <- c('Engineer', 'Doctor', 'Lawyer')

# Add another new column 'Salary' to the dataframe
df$Salary <- c(70000, 80000, 75000)

# Print the updated dataframe
print("Updated Dataframe with New Columns:")
print(df)

Output:

[1] "Original Dataframe:"
      Name Age
1   Alice  25
2     Bob  30
3 Charlie  28

[1] "Updated Dataframe with New Columns:"
      Name Age Occupation Salary
1   Alice  25   Engineer  70000
2     Bob  30     Doctor  80000
3 Charlie  28     Lawyer  75000

4. Step By Step Explanation

- We start by creating an initial dataframe df with columns Name and Age.

- The new columns are added directly by specifying the column name and assigning the respective values. For instance, df$Occupation is used to add a new column named 'Occupation'.

- Ensure that when adding a new column, the length of the data you're adding matches the number of rows in the dataframe.

Comments

Spring Boot 3 Paid Course Published for Free
on my Java Guides YouTube Channel

Subscribe to my YouTube Channel (165K+ subscribers):
Java Guides Channel

Top 10 My Udemy Courses with Huge Discount:
Udemy Courses - Ramesh Fadatare