Hi and welcome to the community!
- The
Invec argument is simply not given a default. That means taht when you call the function you have to pass your own value to that argument. If you do not pass a value to that argument than the function will not run. Conversely, the multiplier argument has a default value of 1, so if you only passed the invec argument to the function when calling it, then it will still run and use 1 as the multiplier value.
- The function certainly has error checking in it, but that is not its main purpose. The purpose of this function is to log transform the data using some multiplier. When writing functions, it is good practice to include error checking steps in order to ensure that the code you are trying to execute correctly is working. We can look at each of these error messages one at a time:
if(!is.numeric(invec) | !is.numeric(multiplier)) {warning(warningmessages[1]); return(NA)}
This line is checking whether the values given to each argument are numeric. If not it returns NA and gives the user a error message
if(any(invec < 0.0) | any(multiplier < 0.0)) {warning(warningmessages[2]); return(NA)}
This line is making sure that none of the values passed to either argument is less than zero because the log of a negative number gives the value of NaN
if(length(multiplier) != 1) {{warning(warningmessages[3]); return(NA)}}
This is ensuring that only a single multiplier is provided
Finally, you get to the actual portion of the code that is doing the desired computation. It is a little confusing because it is in a tryCatch function.
tryCatch(log(multiplier * invec),
error = function(e){warning(warningmessages[4]); NA})
However, this is just a defensive mechanism for programming. They could have simply put log(multiplier*invec) and returned the result. However, what if their manual error catching didn't capture all of the possible ways that that line of code could fail? The tryCatch function will execute the desired command (in this case log(multiplier*invec)) and if the code executes with no error will return the result. If the code fails however, then it will return a more informative error message and an NA value.
- If you wanted to accomplish what this function is doing without the error checking you could simply write:
my_log_trans <- function(invec, multiplier = 1){
log(multiplier * invec)
}
However, I wouldn't recommend removing the error catching as it was likely put there so that the function would work properly