Menu
Coddy logo textTech

Total Spending

Part of the Logic & Flow section of Coddy's R journey. Lesson 58 of 64.

challenge icon

Challenge

Easy

Add the TOTAL command to tracker(). Keep every command from the previous steps working exactly as before.

  • TOTAL: reply total: followed by the sum of all recorded amounts with two decimals, then , count: and the number of expenses, such as total: 512.50, count: 2. With nothing recorded the reply is total: 0.00, count: 0.

The supplied code passes every input line to tracker() as one command and prints each returned reply on its own line. Dates are written YYYY-MM-DD, categories are lower-case words, and the input holds only the commands described so far.

Try it yourself

tracker <- function(commands) {
  expenses <- data.frame(date = character(0), category = character(0), amount = numeric(0))
  replies <- c()
  for (cmd in commands) {
    parts <- strsplit(cmd, " ")[[1]]
    if (parts[1] == "ADD") {
      amount <- suppressWarnings(as.numeric(parts[4]))
      if (length(parts) != 4 || is.na(amount) || amount <= 0) {
        replies <- c(replies, paste("invalid:", cmd))
      } else {
        expenses <- rbind(expenses, data.frame(date = parts[2], category = parts[3], amount = amount))
        replies <- c(replies, sprintf("added %s %.2f", parts[3], amount))
      }
    }
  }
  replies
}

# Supplied input/output code: keep it as it is
input <- suppressWarnings(readLines(file("stdin")))
cat(tracker(input), sep = "\n")

All lessons in Logic & Flow

Practice on your own: Online R compiler