Syntax and Runtime Errors
In R, like in most programming languages, errors can generally be categorized into two main types:
- Syntax Errors
- Runtime Errors
Syntax Errors
Syntax errors occur when the code violates the rules of the R language grammar. These errors are detected before the code is executed (i.e., at parsing time).
Common Causes
- Missing parentheses, brackets, or braces
- Typos in function or variable names
- Incorrect use of operators or punctuation
- Improper string termination
> x <- c(1, 2, 3 # Missing closing parenthesis
> mean[1, 2] # Incorrect use of brackets instead of parentheses
Runtime Errors
Runtime errors occur when R successfully parses the code but encounters a problem during execution. These errors only show up while the code is running.
Common Causes
- Referring to undefined variables
- Invalid data types (e.g., adding a number to a string)
- Index out of bounds
- Division by zero
- Function misuse
> x <- "text"
> y <- x + 1 # Trying to add a number to a string
# Error in x + 1 : non-numeric argument to binary operator
> z <- log(-1)
# Warning message:
# In log(-1) : NaNs produced