R中的" = "和"

时间:2021-12-18 17:17:08

What are the differences between the assignment operators = and <- in R?

赋值运算符=和<- in R之间的区别是什么?

I know that operators are slightly different, as this example shows

我知道运算符有点不同,正如这个例子所示

x <- y <- 5
x = y = 5
x = y <- 5
x <- y = 5
# Error in (x <- y) = 5 : could not find function "<-<-"

But is this the only difference?

但这是唯一的区别吗?

6 个解决方案

#1


508  

The difference in assignment operators is clearer when you use them to set an argument value in a function call. For example:

当您使用它们在函数调用中设置参数值时,赋值操作符的区别就更清楚了。例如:

median(x = 1:10)
x   
## Error: object 'x' not found

In this case, x is declared within the scope of the function, so it does not exist in the user workspace.

在本例中,x是在函数范围内声明的,因此它不存在于用户工作区中。

median(x <- 1:10)
x    
## [1]  1  2  3  4  5  6  7  8  9 10

In this case, x is declared in the user workspace, so you can use it after the function call has been completed.

在本例中,x在用户工作区中声明,因此可以在完成函数调用之后使用它。


There is a general preference among the R community for using <- for assignment (other than in function signatures) for compatibility with (very) old versions of S-Plus. Note that the spaces help to clarify situations like

R社区普遍倾向于使用<- for赋值(函数签名中除外)来与(非常)旧的S-Plus兼容。注意,空格有助于澄清类似的情况

x<-3
# Does this mean assignment?
x <- 3
# Or less than?
x < -3

Most R IDEs have keyboard shortcuts to make <- easier to type. Ctrl + = in Architect, Alt + - in RStudio (Option + - under macOS), Shift + - (underscore) in emacs+ESS.

大多数的R ide都有键盘快捷键,使得<-更容易键入。按Ctrl + =在架构师,Alt + -在RStudio(选项+ -在macOS下),Shift + -(下划线)在emacs+ESS中。


If you prefer writing = to <- but want to use the more common assignment symbol for publicly released code (on CRAN, for example), then you can use one of the tidy_* functions in the formatR package to automatically replace = with <-.

如果您更喜欢编写=而不是<-,但是希望为公开发布的代码(例如在CRAN上)使用更常用的赋值符号,那么您可以使用formatR包中的tidy_*函数之一来自动将=替换为<-。

library(formatR)
tidy_source(text = "x=1:5", arrow = TRUE)
## x <- 1:5

The answer to the question "Why does x <- y = 5 throw an error but not x <- y <- 5?" is "It's down to the magic contained in the parser". R's syntax contains many ambiguous cases that have to be resolved one way or another. The parser chooses to resolve the bits of the expression in different orders depending on whether = or <- was used.

“为什么x <- y = 5抛出一个错误,而不是x <- y <- 5?”R的语法包含了许多不明确的情况,必须以某种方式加以解决。解析器选择根据是否使用=或<-以不同的顺序解析表达式的位。

To understand what is happening, you need to know that assignment silently returns the value that was assigned. You can see that more clearly by explicitly printing, for example print(x <- 2 + 3).

要理解发生了什么,您需要知道这个赋值以静默方式返回所赋值。通过显式打印可以更清楚地看到这一点,例如print(x <- 2 + 3)。

Secondly, it's clearer if we use prefix notation for assignment. So

其次,如果我们使用前缀表示法,它会更清晰。所以

x <- 5
`<-`(x, 5)  #same thing

y = 5
`=`(y, 5)   #also the same thing

The parser interprets x <- y <- 5 as

解析器将x <- y <- 5解释为

`<-`(x, `<-`(y, 5))

We might expect that x <- y = 5 would then be

我们可能期望x <- y = 5

`<-`(x, `=`(y, 5))

but actually it gets interpreted as

但实际上它被解释为

`=`(`<-`(x, y), 5)

This is because = is lower precedence than <-, as shown on the ?Syntax help page.

这是因为=的优先级低于<-,如在语法帮助页上所示。

#2


84  

Google's R style guide simplifies the issue by prohibiting the "=" for assignment. Not a bad choice.

谷歌的R风格指南通过禁止赋值时使用“=”来简化问题。不是一个坏的选择。

https://google.github.io/styleguide/Rguide.xml

https://google.github.io/styleguide/Rguide.xml

The R manual goes into nice detail on all 5 assignment operators.

R手册对所有5个赋值操作符都做了详细说明。

http://stat.ethz.ch/R-manual/R-patched/library/base/html/assignOps.html

http://stat.ethz.ch/R-manual/R-patched/library/base/html/assignOps.html

#3


27  

According to John Chambers, the operator = is only allowed at "the top level," which means it is not allowed in control structures like if, making the following programming error illegal.

根据John Chambers的说法,运算符=只允许在“最高层”,这意味着它不允许出现在像if这样的控制结构中,这使得下面的编程错误成为非法的。

> if(x = 0) 1 else x
Error: syntax error

As he writes, "Disallowing the new assignment form [=] in control expressions avoids programming errors (such as the example above) that are more likely with the equal operator than with other S assignments."

正如他所写的,“在控制表达式中禁止新的赋值形式[=]可以避免编程错误(如上面的示例),与其他S赋值相比,等操作符更可能出现这种错误。”

You can manage to do this if it's "isolated from surrounding logical structure, by braces or an extra pair of parentheses," so if ((x = 0)) 1 else x would work.

如果它“与周围的逻辑结构隔离,通过大括号或一对额外的圆括号”,那么如果((x = 0) 1 else x可以工作的话,您可以这样做。

See http://developer.r-project.org/equalAssign.html

参见http://developer.r-project.org/equalAssign.html

#4


24  

x = y = 5 is equivalent to x = (y = 5), because the assignment operators "group" right to left, which works. Meaning: assign 5 to y, leaving the number 5; and then assign that 5 to x.

x = y = 5等于x = (y = 5),因为赋值运算符“group”从右到左是有效的。意思是:把5赋给y,留下5;然后把5赋给x。

This is not the same as (x = y) = 5, which doesn't work! Meaning: assign the value of y to x, leaving the value of y; and then assign 5 to, umm..., what exactly?

这和(x = y) = 5不一样,它不起作用!把y的值赋给x,留下y的值;然后分配5到。,到底是什么?

When you mix the different kinds of assignment operators, <- binds tighter than =. So x = y <- 5 is interpreted as x = (y <- 5), which is the case that makes sense.

当您混合不同类型的赋值操作符时,<-绑定比=更紧密。所以x = y <- 5被解释为x = (y <- 5)这是有道理的。

Unfortunately, x <- y = 5 is interpreted as (x <- y) = 5, which is the case that doesn't work!

不幸的是,x <- y = 5被解释为(x <- y) = 5,这是行不通的!

See ?Syntax and ?assignOps for the precedence (binding) and grouping rules.

查看?语法和?指定优先级(绑定)和分组规则。

#5


20  

The operators <- and = assign into the environment in which they are evaluated. The operator <- can be used anywhere, whereas the operator = is only allowed at the top level (e.g., in the complete expression typed at the command prompt) or as one of the subexpressions in a braced list of expressions.

运算符<- and =赋值到计算它们的环境中。运算符<-可以在任何地方使用,而运算符=只允许在顶层(例如,在命令提示符键入的完整表达式中)或作为一个带支撑的表达式列表中的子表达式。

#6


4  

This may also add to understanding of the difference between those two operators:

这也可能有助于了解这两个操作符之间的区别:

df <- data.frame(
      a = rnorm(10),
      b <- rnorm(10)
)

For the first element R has assigned values and proper name, while the name of the second element looks a bit strange.

对于第一个元素,R赋值和适当的名称,而第二个元素的名称看起来有点奇怪。

str(df)
# 'data.frame': 10 obs. of  2 variables:
#  $ a             : num  0.6393 1.125 -1.2514 0.0729 -1.3292 ...
#  $ b....rnorm.10.: num  0.2485 0.0391 -1.6532 -0.3366 1.1951 ...

R version 3.3.2 (2016-10-31); macOS Sierra 10.12.1

3.3.2 R版本(2016-10-31);macOS塞拉10.12.1

#1


508  

The difference in assignment operators is clearer when you use them to set an argument value in a function call. For example:

当您使用它们在函数调用中设置参数值时,赋值操作符的区别就更清楚了。例如:

median(x = 1:10)
x   
## Error: object 'x' not found

In this case, x is declared within the scope of the function, so it does not exist in the user workspace.

在本例中,x是在函数范围内声明的,因此它不存在于用户工作区中。

median(x <- 1:10)
x    
## [1]  1  2  3  4  5  6  7  8  9 10

In this case, x is declared in the user workspace, so you can use it after the function call has been completed.

在本例中,x在用户工作区中声明,因此可以在完成函数调用之后使用它。


There is a general preference among the R community for using <- for assignment (other than in function signatures) for compatibility with (very) old versions of S-Plus. Note that the spaces help to clarify situations like

R社区普遍倾向于使用<- for赋值(函数签名中除外)来与(非常)旧的S-Plus兼容。注意,空格有助于澄清类似的情况

x<-3
# Does this mean assignment?
x <- 3
# Or less than?
x < -3

Most R IDEs have keyboard shortcuts to make <- easier to type. Ctrl + = in Architect, Alt + - in RStudio (Option + - under macOS), Shift + - (underscore) in emacs+ESS.

大多数的R ide都有键盘快捷键,使得<-更容易键入。按Ctrl + =在架构师,Alt + -在RStudio(选项+ -在macOS下),Shift + -(下划线)在emacs+ESS中。


If you prefer writing = to <- but want to use the more common assignment symbol for publicly released code (on CRAN, for example), then you can use one of the tidy_* functions in the formatR package to automatically replace = with <-.

如果您更喜欢编写=而不是<-,但是希望为公开发布的代码(例如在CRAN上)使用更常用的赋值符号,那么您可以使用formatR包中的tidy_*函数之一来自动将=替换为<-。

library(formatR)
tidy_source(text = "x=1:5", arrow = TRUE)
## x <- 1:5

The answer to the question "Why does x <- y = 5 throw an error but not x <- y <- 5?" is "It's down to the magic contained in the parser". R's syntax contains many ambiguous cases that have to be resolved one way or another. The parser chooses to resolve the bits of the expression in different orders depending on whether = or <- was used.

“为什么x <- y = 5抛出一个错误,而不是x <- y <- 5?”R的语法包含了许多不明确的情况,必须以某种方式加以解决。解析器选择根据是否使用=或<-以不同的顺序解析表达式的位。

To understand what is happening, you need to know that assignment silently returns the value that was assigned. You can see that more clearly by explicitly printing, for example print(x <- 2 + 3).

要理解发生了什么,您需要知道这个赋值以静默方式返回所赋值。通过显式打印可以更清楚地看到这一点,例如print(x <- 2 + 3)。

Secondly, it's clearer if we use prefix notation for assignment. So

其次,如果我们使用前缀表示法,它会更清晰。所以

x <- 5
`<-`(x, 5)  #same thing

y = 5
`=`(y, 5)   #also the same thing

The parser interprets x <- y <- 5 as

解析器将x <- y <- 5解释为

`<-`(x, `<-`(y, 5))

We might expect that x <- y = 5 would then be

我们可能期望x <- y = 5

`<-`(x, `=`(y, 5))

but actually it gets interpreted as

但实际上它被解释为

`=`(`<-`(x, y), 5)

This is because = is lower precedence than <-, as shown on the ?Syntax help page.

这是因为=的优先级低于<-,如在语法帮助页上所示。

#2


84  

Google's R style guide simplifies the issue by prohibiting the "=" for assignment. Not a bad choice.

谷歌的R风格指南通过禁止赋值时使用“=”来简化问题。不是一个坏的选择。

https://google.github.io/styleguide/Rguide.xml

https://google.github.io/styleguide/Rguide.xml

The R manual goes into nice detail on all 5 assignment operators.

R手册对所有5个赋值操作符都做了详细说明。

http://stat.ethz.ch/R-manual/R-patched/library/base/html/assignOps.html

http://stat.ethz.ch/R-manual/R-patched/library/base/html/assignOps.html

#3


27  

According to John Chambers, the operator = is only allowed at "the top level," which means it is not allowed in control structures like if, making the following programming error illegal.

根据John Chambers的说法,运算符=只允许在“最高层”,这意味着它不允许出现在像if这样的控制结构中,这使得下面的编程错误成为非法的。

> if(x = 0) 1 else x
Error: syntax error

As he writes, "Disallowing the new assignment form [=] in control expressions avoids programming errors (such as the example above) that are more likely with the equal operator than with other S assignments."

正如他所写的,“在控制表达式中禁止新的赋值形式[=]可以避免编程错误(如上面的示例),与其他S赋值相比,等操作符更可能出现这种错误。”

You can manage to do this if it's "isolated from surrounding logical structure, by braces or an extra pair of parentheses," so if ((x = 0)) 1 else x would work.

如果它“与周围的逻辑结构隔离,通过大括号或一对额外的圆括号”,那么如果((x = 0) 1 else x可以工作的话,您可以这样做。

See http://developer.r-project.org/equalAssign.html

参见http://developer.r-project.org/equalAssign.html

#4


24  

x = y = 5 is equivalent to x = (y = 5), because the assignment operators "group" right to left, which works. Meaning: assign 5 to y, leaving the number 5; and then assign that 5 to x.

x = y = 5等于x = (y = 5),因为赋值运算符“group”从右到左是有效的。意思是:把5赋给y,留下5;然后把5赋给x。

This is not the same as (x = y) = 5, which doesn't work! Meaning: assign the value of y to x, leaving the value of y; and then assign 5 to, umm..., what exactly?

这和(x = y) = 5不一样,它不起作用!把y的值赋给x,留下y的值;然后分配5到。,到底是什么?

When you mix the different kinds of assignment operators, <- binds tighter than =. So x = y <- 5 is interpreted as x = (y <- 5), which is the case that makes sense.

当您混合不同类型的赋值操作符时,<-绑定比=更紧密。所以x = y <- 5被解释为x = (y <- 5)这是有道理的。

Unfortunately, x <- y = 5 is interpreted as (x <- y) = 5, which is the case that doesn't work!

不幸的是,x <- y = 5被解释为(x <- y) = 5,这是行不通的!

See ?Syntax and ?assignOps for the precedence (binding) and grouping rules.

查看?语法和?指定优先级(绑定)和分组规则。

#5


20  

The operators <- and = assign into the environment in which they are evaluated. The operator <- can be used anywhere, whereas the operator = is only allowed at the top level (e.g., in the complete expression typed at the command prompt) or as one of the subexpressions in a braced list of expressions.

运算符<- and =赋值到计算它们的环境中。运算符<-可以在任何地方使用,而运算符=只允许在顶层(例如,在命令提示符键入的完整表达式中)或作为一个带支撑的表达式列表中的子表达式。

#6


4  

This may also add to understanding of the difference between those two operators:

这也可能有助于了解这两个操作符之间的区别:

df <- data.frame(
      a = rnorm(10),
      b <- rnorm(10)
)

For the first element R has assigned values and proper name, while the name of the second element looks a bit strange.

对于第一个元素,R赋值和适当的名称,而第二个元素的名称看起来有点奇怪。

str(df)
# 'data.frame': 10 obs. of  2 variables:
#  $ a             : num  0.6393 1.125 -1.2514 0.0729 -1.3292 ...
#  $ b....rnorm.10.: num  0.2485 0.0391 -1.6532 -0.3366 1.1951 ...

R version 3.3.2 (2016-10-31); macOS Sierra 10.12.1

3.3.2 R版本(2016-10-31);macOS塞拉10.12.1