Menu
Coddy logo textTech

Warnings and finally

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

A warning reports a problem without stopping: the function returns a value and R prints the warning at the end. as.numeric() warns for text that is not a number and returns NA:

x <- as.numeric("abc")
print(x)

Output:

[1] NA
Warning message:
NAs introduced by coercion 

Like errors, warnings go to the error stream, so on Coddy they fail a test. suppressWarnings() silences them when you check the result yourself, and tryCatch(..., warning = ) turns a warning into a value:

x <- suppressWarnings(as.numeric("abc"))
print(is.na(x))
r <- tryCatch(as.numeric("abc"), warning = function(w) paste("warned:", conditionMessage(w)))
print(r)

Output:

[1] TRUE
[1] "warned: NAs introduced by coercion"

warning("message") raises a warning from your own code. A handler for it works the same way as one for an error:

ratio <- function(a, b) {
  if (b == 0) warning("b is zero, returning Inf")
  a / b
}
r <- tryCatch(ratio(1, 0), warning = function(w) conditionMessage(w))
print(r)

Output:

[1] "b is zero, returning Inf"

finally = ... runs after the expression and any handler, whether an error happened or not. Use it for work that must always happen, such as a closing message:

load <- function(x) {
  tryCatch({
    if (x < 0) stop("negative")
    x * 10
  }, error = function(e) NA,
  finally = cat("finished", x, "\n"))
}
print(load(2))
print(load(-1))

Output:

finished 2 
[1] 20
finished -1 
[1] NA
challenge icon

Challenge

Easy

Complete to_numbers(texts). Convert every text to a number. Values that cannot be converted become NA without any warning being printed. Return two lines: Numbers: with the converted numbers joined by spaces (the NA values included), and Invalid: with the number of values that failed.

The supplied code reads the texts as a comma-separated line and prints each returned line.

Try it yourself

to_numbers <- function(texts) {
  # Write your code here
  c("Numbers: ", "Invalid: 0")
}

# Supplied input/output code: keep it as it is
input <- suppressWarnings(readLines(file("stdin")))
cat(to_numbers(strsplit(input[1], ",")[[1]]), sep = "\n")
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow

Practice on your own: Online R compiler