函数工厂顾名思义就是生产函数的工厂,你想不想拥有可以批量生产满足自己需求的函数工厂呢?下面我将举个简单的例子来说明函数工厂的威力,其实也可以理解为函数闭包。
## 创建函数工厂:power
power <- function(exponent) {
function(x) {
x ^ exponent
}
}
## 创建平方函数
square <- power(2)
square(2)
# [1] 4
square(4)
# [1] 16
square(99)
# [1] 9801
square(2021)
# [1] 4084441
## 创建立方函数
cube <- power(3)
cube(2)
# [1] 8
cube(3)
# [1] 27
cube(91)
# [1] 753571
cube(2021)
# [1] 8254655261
## 创建8次方函数
octave_power <- power(8)
octave_power(2)
# [1] 256
octave_power(3)
# [1] 6561
octave_power(2021)
# [1] 2.783111e+26
## 创建10次方函数
the_tenth_power <- power(10)
the_tenth_power(2)
# [1] 1024
the_tenth_power(3)
# [1] 59049
the_tenth_power(10)
# [1] 1e+10
类似其他的更实用的函数工厂,其实就是R中基础函数,具体查看The R Base Package中的基础函数。我们可以利用前人已经创建好的基础函数,或者也叫函数工厂来构建自己的自定义的函数,来实现各种计算需求的功能。
head(ls(package:base),n=100)
[1] "-" "-.Date"
[3] "-.POSIXt" ":"
[5] "::" ":::"
[7] "!" "!.hexmode"
[9] "!.octmode" "!="
[11] "(" "["
[13] "[.AsIs" "[.data.frame"
[15] "[.Date" "[.difftime"
[17] "[.Dlist" "[.DLLInfoList"
[19] "[.factor" "[.hexmode"
[21] "[.listof" "[.noquote"
[23] "[.numeric_version" "[.octmode"
[25] "[.POSIXct" "[.POSIXlt"
[27] "[.simple.list" "[.table"
[29] "[.warnings" "[["
[31] "[[.data.frame" "[[.Date"
[33] "[[.factor" "[[.numeric_version"
[35] "[[.POSIXct" "[[.POSIXlt"
[37] "[[<-" "[[<-.data.frame"
[39] "[[<-.factor" "[[<-.numeric_version"
[41] "[[<-.POSIXlt" "[<-"
[43] "[<-.data.frame" "[<-.Date"
[45] "[<-.difftime" "[<-.factor"
[47] "[<-.numeric_version" "[<-.POSIXct"
[49] "[<-.POSIXlt" "{"
[51] "@" "@<-"
[53] "*" "*.difftime"
[55] "/" "/.difftime"
[57] "&" "&.hexmode"
[59] "&.octmode" "&&"
[61] "%*%" "%/%"
[63] "%%" "%in%"
[65] "%o%" "%x%"
[67] "^" "+"
[69] "+.Date" "+.POSIXt"
[71] "<" "<-"
[73] "<<-" "<="
[75] "=" "=="
[77] ">" ">="
[79] "|" "|.hexmode"
[81] "|.octmode" "||"
[83] "~" "$"
[85] "$.DLLInfo" "$.package_version"
[87] "$<-" "$<-.data.frame"
[89] "abbreviate" "abs"
[91] "acos" "acosh"
[93] "activeBindingFunction" "addNA"
[95] "addTaskCallback" "agrep"
[97] "agrepl" "alist"
[99] "all" "all.equal"
print(sessionInfo())
# R version 4.1.0 (2021-05-18)
# Platform: x86_64-apple-darwin17.0 (64-bit)
# Running under: macOS Big Sur 10.16
#
# Matrix products: default
# LAPACK: /Library/Frameworks/R.framework/Versions/4.1/Resources/lib/libRlapack.dylib
#
# locale:
# [1] zh_CN.UTF-8/zh_CN.UTF-8/zh_CN.UTF-8/C/zh_CN.UTF-8/zh_CN.UTF-8
#
# attached base packages:
# [1] stats graphics grDevices utils datasets methods base
#
# loaded via a namespace (and not attached):
# [1] BiocManager_1.30.16 compiler_4.1.0 DBI_1.1.1
# [4] tools_4.1.0 tinytex_0.32 RMySQL_0.10.21
# [7] xfun_0.24
当然,函数工厂的优势在下面的环境中更有用:
1.带有多个参数和复杂的函数体;
2.一劳永逸的创建函数,或者说有规律可循的函数体,只是变换了函数参数,就像上面举的例子,求幂次函数,只是次方不一样,更换次方参数就可以创建对应的求次方函数了。
关于R语言中的函数工厂,你有什么想法,或者你在工作和学习中遇到过哪些函数工厂呢?来一起讨论交流一下吧。