R Program to Add Columns to a Dataframe

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