I want to write a function that applies one of two different statistical methods to its input. In the process, I noticed some behavior of various functions that I do not understand. The function I want to write must have the following properties:
- it should have a vector as the default value (so that the user can see which methods are available)
- if the argument remains the default then use the first of two methods
- if the user manually supplies a vector of methods, then the function should throw an error
Basically, I want the function to behave the way cor does in R. There you have the default value method = c("pearson", "kendall", "spearman") , and the functions calculated the Pearson correlation if method does not indicated. If the user requests several methods at once, the function returns an error.
From a look at cor this seems to be done using match.arg(method) . This behavior is illustrated here:
x <- y <- 1:5 cor(x, y, method="pearson") # = 1 cor(x, y, method="kendall") # = 1 cor(x, y, method=c("pearson","kendall")) # gives an error
I tried to write my own function, also using match.arg(method) , but I realized that the result is somehow different. Even when choosing a vector for method function does not end with an error, but returns the results of the first method.
This is shown here:
myfun <- function(x, method=c("add","multiply")){ method <- match.arg(method) if(method=="add") return(sum(x)) if(method=="multiply") return(prod(x)) } x <- 1:5 myfun(x, method="add")
I do not understand this behavior, and I would be glad if you could help me here. From my attempts at Google, I understand that this may be due to a non-standard assessment, but so far I can’t add two and two.
Thanks in advance, your help is much appreciated!
Hooray!
EDIT:
I could also rephrase my question:
What powerful cor magic does cor make it return Pearson's correlation when method not supplied, but that it returns an error when method = c("pearson", "kendall", "spearman") explicitly indicated?