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
Post a Comment
Leave Comment