首页 > 解决方案 > 将要执行的所有步骤代码一一解释

问题描述

    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

我试图一步一步解释代码以及这些代码如何运行以得到最终输出但不确定它是否正确

标签: r

解决方案


##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.


推荐阅读