Section 8 Error Message
8.1 Condition
| Condition | Explanation |
|---|---|
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. |
8.4 Example 3
printMsg <- function(x) {
if(is.na(x)){
msg <- paste0('Encountered a missing value')
} else if (x == 0) {
msg <- paste0(x, ' is neither a positive nor a negative number')
} else if (x > 0) {
msg <- paste0(x, ' is a positive number')
} else if (x < 0) {
msg <- paste0(x, ' is a negative number')
}
print(msg)
}
printMsg(5)
printMsg(-5)
printMsg(0)
printMsg(NA)
printMsg(c(5, -10, NA))8.5 Example 4
printMsg <- function(x) {
msg <- NULL
if(length(x) > 1){
stop('x should be of length 1')
} else if(is.na(x)){
warning('Encountered a missing value')
} else if (x == 0) {
msg <- paste0(x, ' is neither a positive nor a negative number')
} else if (x > 0) {
msg <- paste0(x, ' is a positive number')
} else if (x < 0) {
msg <- paste0(x, ' is a negative number')
}
if(!is.null(msg)) print(msg)
}
printMsg(5)
printMsg(-5)
printMsg(0)
printMsg(NA)
printMsg(c(0, 5, -10, NA))8.6 Example 5
Vectorize creates a function wrapper that vectorizes the action of its argument FUN.
printMsgNew <- function(x) {
msg <- NULL
if(is.na(x)){
msg <- 'Encountered a missing value'
} else if (x == 0) {
msg <- paste0(x, ' is neither a positive nor a negative number')
} else if (x > 0) {
msg <- paste0(x, ' is a positive number')
} else if (x < 0) {
msg <- paste0(x, ' is a negative number')
}
if(!is.null(msg)) print(msg)
}
printMessageVec <- Vectorize(printMsgNew)
out <- printMessageVec(c(-5,0,5,NA))8.7 Common error messages
Error:
could not find functionError in
iffunction:missing value where TRUE/FALSE is neededError:
Error in eval; object not foundError:
cannot open the connectionError:
incorrect number of dimensionsError:
subscript out of boundsError:
undefined columns selectedError:
non-numeric argument to a binary operatorError:
no applicable method- caused by using an object-oriented function on a data type it does not support