I am new to R and programming in general and am trying to write a very basic function where the input is 2 numbers and a selection from one of 3 operations. The output is supposed to be the result of a further calculation (divide the result of the input by 3*pi) and then a character string to confirm what operation was selected/performed. I want the default operation to be addition.
I've read up a little on the switch function and if... else type statements but not sure what is the most efficient way to achieve what I am trying to do and so far I haven't been able to get anything to work anyway. I seem to be getting a massive matrix as the output or an error to say I can't return multiple arguments in my current attempt. Can someone help with where I am going wrong? Thank you in advance.
basiccalc <- function(x, y, operation = addition){
addition <- x + y
subtraction <- x - y
multiplication <- x * y
calculation <- operation/(3*pi)
return(calculation, "operation")
}
switch
would be useful
basiccalc <- function(x, y, operation = addition) {
operation <- deparse(substitute(operation))
op <- switch(operation,
addition = x + y,
subtraction = x - y,
multiplication = x * y)
return(op/(3 *pi))
}
-testing
> basiccalc(3, 5)
[1] 0.8488264
> 8/(3 * pi)
[1] 0.8488264
> basiccalc(3, 5, operation = subtraction)
[1] -0.2122066
> (3- 5)/(3 * pi)
[1] -0.2122066
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.