R 巢狀函式
巢狀函式
有兩種方法可以建立巢狀函式
- 在一個函式內呼叫另一個函式。
- 在一個函式內編寫一個函式。
示例
在一個函式內呼叫另一個函式
Nested_function <- function(x, y) {
a <- x + y
return(a)
}
Nested_function(Nested_function(2,2), Nested_function(3,3))
自己動手試一試 »
示例解釋
該函式指示 x 和 y 相加。
第一個輸入 Nested_function(2,2) 是主函式的 "x"。
第二個輸入 Nested_function(3,3) 是主函式的 "y"。
因此,輸出是 (2+2) + (3+3) = 10。
示例
在一個函式內編寫一個函式
Outer_func <- function(x) {
Inner_func <- function(y) {
a <- x + y
return(a)
}
return (Inner_func)
}
output <- Outer_func(3) # 呼叫 Outer_func
output(5)
自己動手試一試 »
示例解釋
您無法直接呼叫該函式,因為 Inner_func 已在 Outer_func 內部定義(巢狀)。
我們需要先呼叫 Outer_func,然後才能作為第二步呼叫 Inner_func。
我們需要建立一個名為 output 的新變數,併為其賦值,此處為 3。
然後,我們用所需的 "y" 值(此處為 5)列印輸出。
因此,輸出是 8 (3 + 5)。