R 中恒等函数的实际用途是什么?

发布于 2024-11-30 09:23:59 字数 210 浏览 1 评论 0 原文

Base R 定义了一个identity 函数,一个返回其参数的简单恒等函数(引用自?identity)。

它的定义是:

identity <- function (x){x}

为什么这样一个微不足道的函数会有用?为什么它会被包含在基础 R 中?

Base R defines an identity function, a trivial identity function returning its argument (quoting from ?identity).

It is defined as :

identity <- function (x){x}

Why would such a trivial function ever be useful? Why would it be included in base R?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

今天小雨转甜 2024-12-07 09:24:00

不管它的价值如何,它位于基础包源代码中的 funprog.R(函数式编程的东西)中,并且它在 2008 年被添加为“便利函数”:我可以想象(但不能给出一个直接的例子!)函数式编程方法中会有一些上下文(即使用 FilterReduceMap等等)它会在哪里方便有身份识别功能...

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().

For whatever it's worth, it is located in funprog.R (the functional programming stuff) in the source of the base package, and it was added as a "convenience function" in 2008: I can imagine (but can't give an immediate example!) that there would be some contexts in the functional programming approach (i.e. using Filter, Reduce, Map etc.) where it would be convenient to have an identity function ...

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().
一页 2024-12-07 09:24:00

除了函数式编程之外,identity 还用于 R 中的另一个上下文,即统计。这里用来指代链接函数 ://en.wikipedia.org/wiki/Generalized_linear_model" rel="nofollow">广义线性模型。有关此内容的更多详细信息,请参阅 ?family?glm。这是一个示例:

> x <- rnorm(100)
> y <- rpois(100, exp(1+x))
> glm(y ~x, family=quasi(link=identity))

Call:  glm(formula = y ~ x, family = quasi(link = identity))

Coefficients:
(Intercept)            x
      4.835        5.842

Degrees of Freedom: 99 Total (i.e. Null);  98 Residual
Null Deviance:      6713
Residual Deviance: 2993         AIC: NA

但是,在这种情况下,将其解析为字符串而不是函数将实现相同的效果:glm(y ~x, family=quasi(link="identity"))

编辑:如下面的注释所示,函数 base::identity 不是链接构造函数使用的函数,它仅用于解析链接名称。 (我不会删除这个答案,而是将其保留以帮助澄清两者之间的区别。)

Stepping away from functional programming, identity is also used in another context in R, namely statistics. Here, it is used to refer to the identity link function in generalized linear models. For more details about this, see ?family or ?glm. Here is an example:

> x <- rnorm(100)
> y <- rpois(100, exp(1+x))
> glm(y ~x, family=quasi(link=identity))

Call:  glm(formula = y ~ x, family = quasi(link = identity))

Coefficients:
(Intercept)            x
      4.835        5.842

Degrees of Freedom: 99 Total (i.e. Null);  98 Residual
Null Deviance:      6713
Residual Deviance: 2993         AIC: NA

However, in this case parsing it as a string instead of a function will achieve the same: glm(y ~x, family=quasi(link="identity"))

EDIT: As noted in the comments below, the function base::identity is not what is used by the link constructor, and it is just used for parsing the link name. (Rather than deleting this answer, I'll leave it to help clarify the difference between the two.)

眼泪淡了忧伤 2024-12-07 09:24:00

我只是这样使用它:

fit_model <- function(lots, of, parameters, error_silently = TRUE) {

  purrr::compose(ifelse(test = error_silently, yes = tryNA, no = identity),
                 fit_model_)(lots, of, parameters)
}

tryNA <- function(expr) {
  suppressWarnings(tryCatch(expr = expr,
                            error = function(e) NA,
                            finally = NA))
}

I just used it like this:

fit_model <- function(lots, of, parameters, error_silently = TRUE) {

  purrr::compose(ifelse(test = error_silently, yes = tryNA, no = identity),
                 fit_model_)(lots, of, parameters)
}

tryNA <- function(expr) {
  suppressWarnings(tryCatch(expr = expr,
                            error = function(e) NA,
                            finally = NA))
}
流殇 2024-12-07 09:24:00

由于这个问题已经被查看了 8000 次,因此即使在写完 9 年后也值得更新。

在一篇名为“调试管道的简单技巧(在 magrittr、base R 或 ggplot2 中)”的博客文章中,作者指出了 identity() 在不同类型管道的末尾非常有用。包含示例的博文可以在这里找到:https://rstats-tips.net/2021/06/06/simple-tricks-for-debugging-pipes-within-magrittr-base-r-or-ggplot2/

如果写了管道链在某种程度上,每个“管道”符号都位于行的末尾,您可以通过注释掉任何行来将其从执行中排除。除了最后一行。如果您添加 identity() 作为最后一行,则永远不需要将其注释掉。因此,您可以通过注释掉任何更改数据的行来暂时排除它。

As this question has already been viewed 8k times it maybe worth updating even 9 years after it has been written.

In a blog post called "Simple tricks for Debugging Pipes (within magrittr, base R or ggplot2)" the author points out how identity() can be very usefull at the end of different kinds of pipes. The blogpost with examples can be found here: https://rstats-tips.net/2021/06/06/simple-tricks-for-debugging-pipes-within-magrittr-base-r-or-ggplot2/

If pipe chains are written in a way, that each "pipe" symbol is at the end of a line, you can exclude any line from execution by commenting it out. Except for the last line. If you add identity() as the last line, there will never be a need to comment that out. So you can temporarily exclude any line that changes the data by commenting it out.

静若繁花 2024-12-07 09:24:00

这是用法示例:

    Map<Integer, Long> m = Stream.of(1, 1, 2, 2, 3, 3)
            .collect(Collectors.groupingBy(Function.identity(),
                    Collectors.counting()));
    System.out.println(m);
    output:
    {1=2, 2=2, 3=2}

这里我们将整数分组到 int/count 映射中。 Collectors.groupingBy 接受一个函数。在我们的例子中,我们需要一个返回参数的函数。请注意,我们可以使用 e->e lambda 代替

Here is usage example:

    Map<Integer, Long> m = Stream.of(1, 1, 2, 2, 3, 3)
            .collect(Collectors.groupingBy(Function.identity(),
                    Collectors.counting()));
    System.out.println(m);
    output:
    {1=2, 2=2, 3=2}

here we are grouping ints into a int/count map. Collectors.groupingBy accepts a Function. In our case we need a function which returns the argument. Note that we could use e->e lambda instead

可遇━不可求 2024-12-07 09:24:00

我刚刚使用它将矩阵拆分为其列列表。示例:

(m <- matrix(1:9, 3))
#      [,1] [,2] [,3]
# [1,]    1    4    7
# [2,]    2    5    8
# [3,]    3    6    9

apply(m, 2, identity, simplify = FALSE)
# [[1]]
# [1] 1 2 3
#
# [[2]]
# [1] 4 5 6
#
# [[3]]
# [1] 7 8 9

这里,函数applyidentity函数应用于矩阵m的每一列,即它只返回列。 simplify = FALSE 需要将其保留为列表,而不是简化回数组。

I have just used it to split a matrix into the list of its columns. An example:

(m <- matrix(1:9, 3))
#      [,1] [,2] [,3]
# [1,]    1    4    7
# [2,]    2    5    8
# [3,]    3    6    9

apply(m, 2, identity, simplify = FALSE)
# [[1]]
# [1] 1 2 3
#
# [[2]]
# [1] 4 5 6
#
# [[3]]
# [1] 7 8 9

Here, the function apply applies the identity function to each column of the matrix m, i.e. it just returns the columns. simplify = FALSE needed to keep it as a list rather than simplify back to an array.

久夏青 2024-12-07 09:23:59

不了解 R,但在函数式语言中,人们经常将函数作为参数传递给其他函数。在这种情况下,常量函数(对任何参数都返回相同的值)和恒等函数在乘法中扮演着与 0 和 1 类似的角色。

Don't know about R, but in a functional language one often passes functions as arguments to other functions. In such cases, the constant function (which returns the same value for any argument) and the identity function play a similar role as 0 and 1 in multiplication, so to speak.

夏花。依旧 2024-12-07 09:23:59

我时常将它与命令的 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

I use it from time to time with the apply function of commands.

For instance, you could write t() as:

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
爱她像谁 2024-12-07 09:23:59

出现在简单的 代码库搜索是为了方便 tryCatch 中最基本类型的错误处理函数。

tryCatch(...,error = identity)

这与(哈!)相同,

tryCatch(...,error = function(e) e)

所以这个处理程序会捕获错误消息,然后简单地返回它。

One use that appears on a simple code base search is as a convenience for the most basic type of error handling function in tryCatch.

tryCatch(...,error = identity)

which is identical (ha!) to

tryCatch(...,error = function(e) e)

So this handler would catch an error message and then simply return it.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文