Recap - Safe Calculator
Part of the Logic & Flow section of Coddy's R journey. Lesson 56 of 64.
Challenge
HardComplete evaluate(expr). An expression is <number> <operator> <number> with spaces around the operator, such as 8 / 2. Raise errors with stop() for each problem, checked in this order:
expected: number operator numberwhen there are not exactly three parts'<part>' is not a numberfor the first number part that cannot be converted, such as'x' is not a numberunknown operator <op>when the operator is not+,-,*or/division by zero
Otherwise return the result, rounded to four decimal places with round(value, 4).
Then complete run_all(exprs): evaluate each expression inside tryCatch() and return one line per expression, 8 / 2 = 4 or 5 / 0 -> error: division by zero.
The supplied code passes every input line to run_all() and prints each returned line.
Try it yourself
evaluate <- function(expr) {
# Write your code here
0
}
run_all <- function(exprs) {
# Write your code here
character(0)
}
# Supplied input/output code: keep it as it is
input <- suppressWarnings(readLines(file("stdin")))
cat(run_all(input), sep = "\n")
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 Desk8Sorting and Grouping
Sorting VectorsSorting by a KeyGrouping with split()Group SummariesRecap - Leaderboard11Error Handling
Raising Errors with stop()Catching with tryCatch()Warnings and finallyValidating InputRecap - Safe Calculator3Sets 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