0
0
R Programmingprogramming~5 mins

Adding and removing columns in R Programming

Choose your learning style9 modes available
Introduction

We add or remove columns in a table to change what information it holds. This helps us organize or update data easily.

You want to add a new detail to a list of people, like their age.
You need to remove a column that is no longer useful or has wrong data.
You want to prepare data by selecting only the columns needed for analysis.
You want to combine data by adding columns from another table.
Syntax
R Programming
dataframe$new_column <- values  # Add a new column

dataframe$column_to_remove <- NULL  # Remove a column

Use the $ sign to add or remove columns by name.

Assigning NULL to a column removes it from the dataframe.

Examples
This adds a new column 'city' with values "NY" and "LA" to the dataframe.
R Programming
df <- data.frame(name = c("Anna", "Bob"), age = c(25, 30))
df$city <- c("NY", "LA")
This removes the 'age' column from the dataframe.
R Programming
df$age <- NULL
Adds a new column 'country' with the same value "USA" for all rows.
R Programming
df["country"] <- "USA"
Sample Program

This program creates a table with names and scores. Then it adds a grade column and removes the score column. Finally, it prints the updated table.

R Programming
df <- data.frame(name = c("Alice", "John"), score = c(90, 85))

# Add a new column 'grade'
df$grade <- c("A", "B")

# Remove the 'score' column
df$score <- NULL

print(df)
OutputSuccess
Important Notes

When adding a column, make sure the number of values matches the number of rows.

Removing a column by assigning NULL deletes it permanently from the dataframe.

Summary

Use $ to add or remove columns in a dataframe.

Assign values to add a column; assign NULL to remove one.

Adding/removing columns helps keep your data organized and relevant.