And*_*rie 33 identity functional-programming r
Base R定义了一个identity函数,一个返回其参数的普通身份函数(引用自?identity).
它被定义为:
identity <- function (x){x}
Run Code Online (Sandbox Code Playgroud)
为什么这样一个微不足道的功能会有用呢?为什么它会包含在基础R中?
Ing*_*ngo 15
不了解R,但在函数式语言中,经常将函数作为参数传递给其他函数.在这种情况下,常量函数(对任何参数返回相同的值)和标识函数在乘法中扮演类似0和1的角色,可以这么说.
Ari*_*man 10
我不时使用命令的apply函数.
例如,您可以写t()为:
dat <- data.frame(x=runif(10),y=runif(10))
apply(dat,1,identity)
[,1] [,2] [,3] [,4] [,5] [,6] [,7]
x 0.1048485 0.7213284 0.9033974 0.4699182 0.4416660 0.1052732 0.06000952
y 0.7225307 0.2683224 0.7292261 0.5131646 0.4514837 0.3788556 0.46668331
[,8] [,9] [,10]
x 0.2457748 0.3833299 0.86113771
y 0.9643703 0.3890342 0.01700427
Run Code Online (Sandbox Code Playgroud)
在简单的代码库搜索中出现的一种用途是为了方便最基本类型的错误处理函数tryCatch.
tryCatch(...,error = identity)
Run Code Online (Sandbox Code Playgroud)
这是相同的(哈!)
tryCatch(...,error = function(e) e)
Run Code Online (Sandbox Code Playgroud)
因此,此处理程序将捕获错误消息,然后只返回它.
无论它有什么价值,它都位于funprog.R基础软件包源代码中的(函数式编程),并在2008年被添加为"便利函数":我可以想象(但不能给出一个直接的例子!)会有在函数式编程方法某些情况下(即使用Filter,Reduce,Map等),它是方便的标识功能...
r45063 | hornik | 2008-04-03 12:40:59 -0400 (Thu, 03 Apr 2008) | 2 lines
Add higher-order functions Find() and Position(), and convenience
function identity().
Run Code Online (Sandbox Code Playgroud)