f<-function(x) #build the first function f()#
{
f<-function(x) #define the second function f() within first ##f() function##
{
f<-function(x) #define the third function f() within the ##second f() function and within the first f() function ##
{
x^2 #within the second function of f we define a variable ##f, i.e.f(x)=x^2 ##
}
f(x)+1 #within the first function f we define another variable f, i.e.f(x)=x^2+1#
}
f(x)+2# R looking for the second varible f it takes the defintion of f as varible within the first function of f()#i.e.(x^2+1)+2
}
f(10)
## 10^2=100, 100+1=101, 101+2=103
## ((10^2)+1)+2=103
我试图逐步解释这些代码,以及这些代码如何一步一步地运行以获取最终输出,但不确定是否正确
答案 0 :(得分:0)
##defining the function f(g(h(x)))
##f(x) = g(x) + 2; g(x) = h(x) + 1; h(x) = x^2
f <- function ( x ) {
g <- function ( x ) {
h <- function ( x ) {
x ^ 2 ##computing h(x)
}
h(x) + 1 ##computing g(x)
}
return(g(x) + 2) ##returning final output; computing f(x)
}
f(10)
> 103
这就是我要做的。我认为您的解释有些冗长,将f定义为一个以上的函数通常是个坏主意。如果您不愿意使用f作为函数名称,请在其后添加一个数字。 f1
,f2
,f3
。