Adding and Sorting
Part of the Logic & Flow section of Coddy's R journey. Lesson 45 of 64.
Assigning to a new column name adds the column. Arithmetic between columns works row by row, like any vector arithmetic:
orders <- data.frame(item = c("tea", "jam", "oil"), qty = c(2, 5, 1), price = c(4, 2.5, 9))
orders$total <- orders$qty * orders$price
print(orders)Output:
item qty price total
1 tea 2 4.0 8.0
2 jam 5 2.5 12.5
3 oil 1 9.0 9.0df[order(df$col), ] sorts the rows by a column. The row numbers on the left stay attached to the original rows. Use a minus sign or decreasing = TRUE for high to low, and a second key for ties:
orders <- data.frame(item = c("tea", "jam", "oil"), qty = c(2, 5, 1), price = c(4, 2.5, 9))
orders$total <- orders$qty * orders$price
print(orders[order(-orders$total, orders$item), c("item", "total")])Output:
item total
2 jam 12.5
3 oil 9.0
1 tea 8.0A new column can be text built from other columns. sprintf() works on whole columns at once:
orders <- data.frame(item = c("tea", "jam"), qty = c(2, 5), price = c(4, 2.5))
orders$label <- sprintf("%d x %s", orders$qty, orders$item)
print(orders$label)Output:
[1] "2 x tea" "5 x jam"rbind() adds a row from a one-row data frame with the same columns, and head(df, n) keeps the first n rows:
orders <- data.frame(item = c("tea", "jam"), qty = c(2, 5))
orders <- rbind(orders, data.frame(item = "oil", qty = 1))
print(nrow(orders))
print(head(orders[order(-orders$qty), ], 2))Output:
[1] 3
item qty
2 jam 5
1 tea 2Challenge
EasyComplete order_totals(df). df has the columns item, qty and price. Add a total column (quantity times price), sort the rows by total from high to low (items with equal totals alphabetically), and return one line per row, jam: 12.50, with the total to two decimals.
The supplied code reads the table from the input with read.csv(text = input): the first line holds the column names and every following line is one row, with values separated by commas. The code prints each returned line.
Try it yourself
order_totals <- function(df) {
# Write your code here
character(0)
}
# Supplied input/output code: keep it as it is
input <- suppressWarnings(readLines(file("stdin")))
df <- read.csv(text = input)
cat(order_totals(df), sep = "\n")
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Strings In Depth
Substrings with substr()Formatting with sprintf()Splitting and JoiningSearching StringsReplacing TextRecap - Username Builder4Matrices
Creating MatricesIndexing MatricesRow and Column SummariesMatrix ArithmeticRecap - Seating Chart2Key-Value Lookups
Named Vector LookupsChecking KeysAdding and Removing KeysLooping Over NamesRecap - Stock Desk3Sets and Counting
Unique ValuesSet OperationsMembership TestsCounting with table()Recap - Event Guests6Functions as Values
Anonymous FunctionsPassing FunctionsReturning FunctionsClosures with StateRecap - Discount Rules9Data Frames
Creating Data FramesColumns and RowsFiltering RowsAdding and SortingRecap - Sales Report12Project - Expense Tracker
Recording ExpensesTotal SpendingPractice on your own: Online R compiler