R中类似lambda的函数? [英] lambda-like functions in R?

查看:426
本文介绍了R中类似lambda的函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在uni上学习/使用R进行新的讲座,而我目前在语法上有些挣扎.我想(通过curve)绘制一个简单的函数,但似乎无法将其与内联lambda式函数一起使用.

I’m required to use/learn R for a new lecture at uni and I’m currently struggling a bit with its syntax. I want to plot (via curve) a simple function, but I can’t seem to get it working with an inline lambda-like function.

我尝试了以下操作:

> curve( function(x) x^2 )
Error in curve(function(x) x^2) : 
  'expr' did not evaluate to an object of length 'n'

但是当我首先将函数存储在变量中时,它会起作用:

When I however store the function in a variable first, it works:

> quad <- function(x) x^2
> curve( quad )

R中不允许这样的内联用法吗?还有其他方法可以在不定义额外功能的情况下进行此工作吗?谢谢!

Is such an inline use not allowed in R? Is there any other way to make this work without defining an extra function? Thanks!

推荐答案

您必须查看curve的来源以了解正在发生的事情(只需在提示符下键入curve并按Enter).

You have to look at the source of curve to appreciate what is happening (just type curve at the prompt and press enter).

您可以找到如何解析传递的表达式.

There you can find how the expression passed is parsed.

发现函数的唯一方法就是仅传递其名称(请参见is.name部分).如果不是这种情况,则每个x都会调用该表达式.在您的情况下:对于每个x,结果都是一个函数,对于绘制...来说,这不是一个快乐的想法.

The only way a function is discovered as being just that, is when only its name is passed along (see the is.namepart). If that is not the case, the expression is called for every x. In your case: for every x, the result is a function, which is not a happy thought for plotting...

因此,简而言之:不,您不能做您尝试做的事情,但是正如@ROLO所示,您可以立即传递函数主体,该主体将被解析为一个表达式(并应包含x).如果其中包含多个语句,则将它们括在花括号中.

So in short: no you cannot do what you tried, but as @ROLO indicated, you can immediately pass the function body, which will be parsed as an expression (and should contain x). If this holds multiple statements, just enclose them in curly braces.

这篇关于R中类似lambda的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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