R中函数的语法?

Chi*_*cht 2 syntax r

以下两个是等价的,即它们是否定义了相同的功能?

function(df) {lm(mpg ~ wt, data=df)}
Run Code Online (Sandbox Code Playgroud)

function(df) lm(mpg ~ wt, data=df)
Run Code Online (Sandbox Code Playgroud)

特别是,我很困惑为什么可以在R中编写没有花括号的函数.

当函数定义扩展到多行时,是否只需要大括号来定义函数?

(也许关于R和Python技术上如何支持来自C的分号,但是使用它们被认为是不好的做法?)

这似乎可以解释为什么人们在定义匿名函数时通常不使用大括号,因为匿名函数通常很短,因此可以放在一行上,因此不需要大括号.

但是可以传递定义超过一行的匿名函数(显然这可能是不好的做法,但这不是我的观点)?

如果有可能,那是否需要大括号?

jog*_*ogo 10

您的示例与匿名函数无关.如果它们之间只有一个表达式,则它是关于{}不需要的.
- 表达式可以长于一行.
- 在一行上可以有多个表达式(以分号分隔).
- 匿名函数不限于一行.

您可以{像往常一样找到文档:help('{')

例子:

x <- 3; y <- 4; z <- x + y  # more than one expression on a line

z <- x +
y +
2  # the expression x+y+2 extends over three lines

x <- matrix(1:30,3)
apply(x, 1, function(x) sd(x)/
median(x)) # anonymous function definition on two lines
Run Code Online (Sandbox Code Playgroud)

有时必须小心代码中的换行符.在某些情况下,它们被解释器识别为句法单元的末尾.在这种情况下"小心"意味着:
给译员一个搜索下一行的理由.
这不起作用:

x <- 11:15
x
[3]  # because of the linebreak it is not x[3]
Run Code Online (Sandbox Code Playgroud)

但这样做:

x[
3
]
# the interpreter was searching for the ']' (till it was found)
Run Code Online (Sandbox Code Playgroud)

这是我吸取教训的情况:

if (...) { ... }
else { ... }     # unexpected 'else' !!!
Run Code Online (Sandbox Code Playgroud)

从那时起,我就是这样写的:

if (...) {
   ...
} else {
   ...
}
Run Code Online (Sandbox Code Playgroud)

请参阅"else"错误中的意外"其他"

一个非匿名函数(即命名函数)不是别的,正是通过分配的对象名连接的功能定义:

fname <- function(...) ...
Run Code Online (Sandbox Code Playgroud)

供以后重复使用.您甚至可以在通常可以找到匿名函数的地方执行此操作:

x <- matrix(1:30,3)
apply(x, 1, FUN=(mysuperfunc <- function(x) sd(x)/median(x)) ) 
Run Code Online (Sandbox Code Playgroud)

但这有着更好的可读性:

mysuperfunc <- function(x) sd(x)/median(x)
x <- matrix(1:30,3)
apply(x, 1, FUN=mysuperfunc)
Run Code Online (Sandbox Code Playgroud)

  • 你应该指出{{. (3认同)