R中`=`和`<-`有什么区别?

发布于 2024-08-21 15:47:09 字数 91 浏览 8 评论 0 原文

我使用的是 R 2.8.1,可以使用 =<- 作为变量赋值运算符。他们之间有什么区别?我应该使用哪一个?

I'm using R 2.8.1 and it is possible to use both = and <- as variable assignment operators. What's the difference between them? Which one should I use?

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

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

发布评论

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

评论(2

夏日浅笑〃 2024-08-28 15:47:09

来自此处

运算符 <- 和 = 分配到计算它们的环境中。运算符 <- 可以在任何地方使用,而运算符 = 只允许在顶层(例如,在命令提示符下键入的完整表达式中)或作为括号表达式列表中的子表达式之一。

From here:

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.

蘑菇王子 2024-08-28 15:47:09

阅读 Robert 和 Casella 所著的《R 蒙特卡罗方法简介》:

“赋值运算符是 =,不要与 == 混淆,后者是布尔运算符较旧的赋值运算符是 <- ,出于兼容性原因,它仍然保持功能,但应忽略它以确保更清晰的编程。
例外,因为随后使用 = 来标识关键字)

(正如 Spector, P. (2009).“使用 R 进行数据操作”- 第 8.7 节所指出的,使用 system.time 时是一个 布尔值中存在赋值运算符 <- 的误导性特征
诸如

> if (x[1]<-2) ...

which的表达式应该测试x[1]是否小于-2但结束
将 2 分配给 x[1],擦除其当前值!另请注意,

> if (x[1]=-2) ...

错误地使用 (x[1]==-2) 会产生相同的后果。”

Reading from "Introducing Monte Carlo Methods with R", by Robert and Casella:

"The assignment operator is =, not to be confused with ==, which is the Boolean operator for equality. An older assignment operator is <- and, for compatibility reasons, it still remains functional, but it should be ignored to ensure cleaner programming.
(As pointed out by Spector, P. (2009). 'Data Manipulation with R' - Section 8.7., an exception is when using system.time, since = is then used to identify keywords)

A misleading feature of the assignment operator <- is found in Boolean
expressions such as

> if (x[1]<-2) ...

which is supposed to test whether or not x[1] is less than -2 but ends
up allocating 2 to x[1], erasing its current value! Note also that using

> if (x[1]=-2) ...

mistakenly instead of (x[1]==-2) has the same consequence."

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