简体   繁体   English

在 R 函数中将对象分配给 arguments - 开关,if else 语句或函数?

[英]Assigning objects to arguments in R functions - switches, if else statements or functions?

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.我是 R 和一般编程的新手,我正在尝试编写一个非常基本的 function,其中输入是 2 个数字并从 3 个操作之一中进行选择。 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. output 应该是进一步计算的结果(将输入的结果除以 3*pi),然后是一个字符串,以确认选择/执行的操作。 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.我已经阅读了一些关于开关 function 和 if...else 类型的语句,但不确定什么是实现我想要做的最有效的方法,到目前为止我还没有能够得到任何工作反正。 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.我似乎得到了一个巨大的矩阵,如 output 或者说我在当前尝试中无法返回多个 arguments 的错误。 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 switch会很有用

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM