0
0
R Programmingprogramming~5 mins

mutate() for new columns in R Programming

Choose your learning style9 modes available
Introduction

The mutate() function helps you add new columns or change existing ones in a table of data easily.

You want to calculate a new value based on existing columns, like total price from quantity and price per item.
You need to add a column that shows a category based on some condition.
You want to create a new column that transforms data, like converting temperatures from Celsius to Fahrenheit.
You want to keep your original data but add extra information in new columns for analysis.
Syntax
R Programming
mutate(data_frame, new_column = expression, ...)

data_frame is your table of data.

You can add one or more new columns by giving each a name and a formula.

Examples
Adds a new column total by multiplying price and quantity.
R Programming
mutate(df, total = price * quantity)
Adds two new columns: discount_price and tax calculated from price.
R Programming
mutate(df, discount_price = price * 0.9, tax = price * 0.1)
Adds a new column category that labels rows as "Pass" or "Fail" based on score.
R Programming
mutate(df, category = ifelse(score > 50, "Pass", "Fail"))
Sample Program

This program creates a small table with names, prices, and quantities. Then it adds a new column total by multiplying price and quantity. Finally, it prints the new table.

R Programming
library(dplyr)
df <- data.frame(name = c("Anna", "Ben", "Cara"), price = c(10, 20, 15), quantity = c(2, 1, 3))
df_new <- mutate(df, total = price * quantity)
print(df_new)
OutputSuccess
Important Notes

mutate() does not change the original data unless you save the result.

You can use many functions inside mutate() like ifelse(), arithmetic, or string functions.

Summary

mutate() adds or changes columns in your data.

Use it to create new information from existing data easily.

Remember to save the result if you want to keep the changes.