Adding Students
Part of the Logic & Flow section of Coddy's R journey. Lesson 22 of 64.
In this project you build a gradebook that reads commands, one per line, and replies to each one. Over five steps it learns to add students, record grades, report averages and find the top student. Every step extends the same gradebook(commands) function.
ADD ada
GRADE ada 90
AVG ada
REPORT
TOPThe grades live in a named list: each student's name maps to a numeric vector of that student's grades. A list fits because every student holds several values.
grades <- list()
grades[["ada"]] <- numeric(0)
grades[["ada"]] <- c(grades[["ada"]], 90)
print(length(grades[["ada"]]))
print(names(grades))Output:
[1] 1
[1] "ada"numeric(0) is an empty numeric vector. Assigning c() would not work here: it is NULL, and assigning NULL removes a list entry.
Each command is split at spaces, so parts[1] is the command and parts[2] the name. An if / else if chain picks what to do:
for (cmd in commands) {
parts <- strsplit(cmd, " ")[[1]]
name <- parts[2]
if (parts[1] == "ADD") {
# handle ADD
}
}The replies are collected with replies <- c(replies, ...) and returned at the end.
Challenge
EasyComplete gradebook(commands) for the first command:
ADD <name>: if the student is new, store them with no grades and replyadded <name>. If the name is already stored, reply<name> already exists.
The supplied code passes every input line to gradebook() as one command and prints each returned reply on its own line. A name is one lower-case word, and the input holds only the commands described so far.
Try it yourself
gradebook <- function(commands) {
grades <- list()
replies <- c()
for (cmd in commands) {
parts <- strsplit(cmd, " ")[[1]]
name <- parts[2]
# Write your code here
}
replies
}
# Supplied input/output code: keep it as it is
input <- suppressWarnings(readLines(file("stdin")))
cat(gradebook(input), 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