R:让一个函数调用其他函数并将参数传递给它们
R: Having one function call other functions as well as passing arguments on to them
我有一系列像这样的功能:
otherfunction<-function(x, y){
if(option=="one"){
z<-x+y+var
}
if(option=="two"){
z<-x-y+2*var
}
return(z)
}
然后是定义需要传递的参数的主函数,连同内部函数的输出,到其他内部函数函数,以及。
master <- function(x, y, option=c("one", "two"), variable=0.1){
w <- otherfunction(x,y)
#(or otherfunction(x,y, option, variable))
v <- otherfunction(w,y)
return(v)
}
我似乎遇到了 "object not found" 或 "unused arguments" 错误。
其他人如何处理从主函数调用的多个函数?
我是否需要将 master 函数中的参数值转换为对象?
这个需要在全局环境下做吗?
我需要在 master 函数中定义 "otherfunction" 吗?
我需要使用某种“...”参数吗?
或者还有其他我没有得到的东西吗?
您的 otherfunction
无法从您的 master
函数中查看 option
值。函数在定义它们的环境中查找变量,而不是在它们被调用的地方。这应该有效
otherfunction<-function(x, y, option, var){
if(option=="one"){
z<-x+y+var
}
if(option=="two"){
z<-x-y+2*var
}
return(z)
}
master <- function(x, y, option=c("one", "two"), variable=0.1){
w <- otherfunction(x,y, option, variable)
v <- otherfunction(w,y, option, variable)
return(v)
}
master(2,2, "two")
# [1] -1.6
如果你想传递参数,你也可以用master
做这样的事情
master <- function(x, y, ...){
w <- otherfunction(x,y, ...)
v <- otherfunction(w,y, ...)
return(v)
}
master(2,2, option="two", var=0.1)
# [1] -1.6
我有一系列像这样的功能:
otherfunction<-function(x, y){
if(option=="one"){
z<-x+y+var
}
if(option=="two"){
z<-x-y+2*var
}
return(z)
}
然后是定义需要传递的参数的主函数,连同内部函数的输出,到其他内部函数函数,以及。
master <- function(x, y, option=c("one", "two"), variable=0.1){
w <- otherfunction(x,y)
#(or otherfunction(x,y, option, variable))
v <- otherfunction(w,y)
return(v)
}
我似乎遇到了 "object not found" 或 "unused arguments" 错误。
其他人如何处理从主函数调用的多个函数? 我是否需要将 master 函数中的参数值转换为对象?
这个需要在全局环境下做吗?
我需要在 master 函数中定义 "otherfunction" 吗?
我需要使用某种“...”参数吗?
或者还有其他我没有得到的东西吗?
您的 otherfunction
无法从您的 master
函数中查看 option
值。函数在定义它们的环境中查找变量,而不是在它们被调用的地方。这应该有效
otherfunction<-function(x, y, option, var){
if(option=="one"){
z<-x+y+var
}
if(option=="two"){
z<-x-y+2*var
}
return(z)
}
master <- function(x, y, option=c("one", "two"), variable=0.1){
w <- otherfunction(x,y, option, variable)
v <- otherfunction(w,y, option, variable)
return(v)
}
master(2,2, "two")
# [1] -1.6
如果你想传递参数,你也可以用master
master <- function(x, y, ...){
w <- otherfunction(x,y, ...)
v <- otherfunction(w,y, ...)
return(v)
}
master(2,2, option="two", var=0.1)
# [1] -1.6