R Laanguage: Something’s Wrong!

0

R has a number of ways to indicate to you that something’s not right. There are different levels of indication that can be used, ranging from mere notification to fatal error.

  • message: A generic notification/diagnostic message produced by the message() function; execution of the function continues
  • warning: An indication that something is wrong but not necessarily fatal; execution of the function continues. Warnings are generated by the warning() function
  • error: An indication that a fatal problem has occurred and execution of the function stops. Errors are produced by the stop() function
  • condition: A generic concept for indicating that something unexpected has occurred; programmers can create their own custom conditions if they want.

> printmessage <- function(x) {
+         if(x > 0)
+                 print("x is greater than zero")
+         else
+                 print("x is less than or equal to zero")
+         invisible(x)        
+ }

The function printmessage() has a bug in it. If you pass it a NA value, it will crash with an error. This is because the if statement inside the function cannot handle NA values.

We can fix this bug by adding an if statement to check for NA values. The new function, printmessage2(), will print a message if the input is NA, or it will print the appropriate message if the input is positive or negative.

> printmessage2 <- function(x) {

+         if(is.na(x))

+                 print("x is a missing value!")

+         else if(x > 0)

+                 print("x is greater than zero")

+         else

+                 print("x is less than or equal to zero")

+         invisible(x)

+ }

The function printmessage2() is not vectorized. This means that if you pass it a vector, it will only work for the first element in the vector. To fix this, we can use the Vectorize() function. The new function, printmessage4(), will work for vectors of any length.

> printmessage4 <- Vectorize(printmessage2)

> out <- printmessage4(c(-1, 2))

[1] "x is less than or equal to zero"

[1] "x is greater than zero"

Post a Comment

0Comments
Post a Comment (0)