R Program to Add Rows 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

Adding rows to a dataframe is a common operation when working with datasets in R. This can be particularly useful when aggregating data from different sources or appending new data to an existing dataframe.

2. Program Overview

1. Create an initial dataframe.

2. Add new rows using the rbind() function.

3. Code Program

# Load necessary libraries
library(dplyr)

# Create an initial dataframe
df <- data.frame(
  Name = c('Alice', 'Bob'),
  Age = c(25, 30),
  City = c('New York', 'Los Angeles')
)

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

# Data for the new rows
new_rows <- data.frame(
  Name = c('Charlie', 'David'),
  Age = c(28, 35),
  City = c('Chicago', 'San Francisco')
)

# Append new rows to the dataframe using rbind
df_updated <- rbind(df, new_rows)

# Print the updated dataframe
print("Updated Dataframe with New Rows:")
print(df_updated)

Output:

[1] "Original Dataframe:"
    Name Age         City
1 Alice  25     New York
2   Bob  30  Los Angeles

[1] "Updated Dataframe with New Rows:"
      Name Age           City
1   Alice  25       New York
2     Bob  30    Los Angeles
3 Charlie  28        Chicago
4   David  35 San Francisco

4. Step By Step Explanation

- We first create an initial dataframe df with columns Name, Age, and City.

- New rows to be added are then created in the new_rows dataframe.

- The rbind() function is used to append the rows from new_rows to df. This function combines the rows of two or more data frames.

- Note that the column names and structures of the dataframes being combined using rbind must match.

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