I am writing a function that passes in a vector of values, and I want to use those values for computation within the function. However, I also want to use the name of the vector that I pass to return meaningful error messages but can not figure out how to do so.
My function looks like this
func <- function(vector, minimumvalue){
if(length(vector)==1){
return(1)}
else if (length(vector)<minimumvalue){
stop(paste0("The length of vector is less than ",minimumvalue))}
else if (length(vector)>minimumvalue){
stop(paste0("The length of vector is more than ",minimumvalue))}
else (return(vector))
}
My function call looks like this
colours <- c("red","green","blue")
func(colours, 2)
An returns
"The length of vector is more than 2", but I would like to say "The length of colours is more than 2"
I can achieve this by adding another parameter which passes the name of the vector as a string into the function, but I would like to know if there is a better way to design this.
CodePudding user response:
I added deparse(substitute(vector))
to get the name of the object as a string.
func <- function(vector, minimumvalue){
if(length(vector)==1){
return(1)}
else if (length(vector)<minimumvalue){
stop(paste0("The length of ",deparse(substitute(vector))," is less than ",minimumvalue))}
else if (length(vector)>minimumvalue){
stop(paste0("The length of ",deparse(substitute(vector))," is more than ",minimumvalue))}
else (return(vector))
}
colours <- c("red","green","blue")
func(colours, 2)
Error in func(colours, 2) : The length of colours is more than 2
CodePudding user response:
With the glue
library, you could format the string easier:
library(glue)
func <- function(vector, minimumvalue){
if(length(vector)==1){
return(1)}
else if (length(vector)<minimumvalue){
stop(paste0(glue("The length of vector is less than "),minimumvalue))}
else if (length(vector)>minimumvalue){
stop(paste0(glue("The length of {substitute(vector)} is more than "),minimumvalue))}
else (return(vector))
}
colours <- c("red","green","blue")
func(colours, 2)
Output:
Error in func(colours, 2) :
The length of colours is more than 2
Or even better to use the glue
module for formatting minimumvalue
as well:
library(glue)
func <- function(vector, minimumvalue){
if(length(vector)==1){
return(1)}
else if (length(vector)<minimumvalue){
stop(glue("The length of {substitute(vector)} is less than {minimumvalue}"))}
else if (length(vector)>minimumvalue){
stop(glue("The length of {substitute(vector)} is more than {minimumvalue}"))}
else (return(vector))
}
colours <- c("red","green","blue")
func(colours, 2)
The you don't even need paste0
.