R中的函数(x):写入“函数”没有定义一个函数? [英] function(x) in R: writing a "function" without defining a function?

查看:176
本文介绍了R中的函数(x):写入“函数”没有定义一个函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我偶然遇到过这个概念,但不知道它的名字,所以无法谷歌它学习更多。基本上,当查看其他人写过的函数或简单的命令时,我经常会看到类似这样的内容:

I have come across this concept a couple of times, but don't know the name for it so cannot google it to learn more. Basically, when looking through functions or even simple commands others have written I will often see something similar to this:

apply(dataset, 1:2, function(x) 10 * x)

在这种情况下,出于某种原因,这个假功能 function(x)只会将数据集的每个元素乘以10.这似乎是一个有用的功能,但我仍然不确定何时或如何使用它。它真的是一个功能吗?或者它只是在适用的功能家族中起作用?这个东西有没有名字?

In this case, I was able to figure out that somehow this "fake function" function(x) would just multiply each element of the dataset by 10. This seems like a useful feature, but I'm still not certain when or how you use it. Is it really a function? Or does it just work within the apply family of functions? Is there a name for this thing?

推荐答案

这些被称为匿名函数,是的,它们是真正的函数对象,恰好没有被赋值到任何符号使用之前。

Those are called "anonymous functions", and yes, they are real function objects, which just happen to have not been assigned to any symbol before being used.

以下是来自 R语言文档 b
$ b

Here's the relevant bit from the R language documentation:


函数被分配给符号,但他们不需要。调用函数返回的值是一个函数。如果没有给出名称,则称其为匿名函数。匿名函数最常用作其他函数的参数,如应用系列或外部函数。

虽然它们通常用于 * apply()函数中,但它们不需要,如在这里可以看到的,例如

Although they are most typically used in *apply() functions, they need not be, as can be seen here, for example

(function(x,y){x*y + x/y})(2,5)
# [1] 10.4

这篇关于R中的函数(x):写入“函数”没有定义一个函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆