【发布时间】:2018-02-12 02:21:53
【问题描述】:
【问题讨论】:
-
一个通用的“规则”:在提出新问题之前进行搜索。我通过搜索“[r] assignment”找到了答案。
-
@CodyGray 感谢您的编辑 -- 这样好多了。
-
@samcarter 非常感谢。
标签: r google-style-guide
【问题讨论】:
标签: r google-style-guide
我相信有两个原因。一是<- 和= 的含义会根据上下文略有不同。例如,比较语句的行为:
printx <- function(x) print(x)
printx(x="hello")
printx(x<-"hello")
在第二种情况下,printx(x<-"hello") 也会分配给父作用域,而 printx(x="hello") 只会设置参数。
另一个原因是出于历史目的。 R、S 和它们所基于的“APL”语言都只允许使用箭头键进行分配(历史上只有一个字符)。参考:http://blog.revolutionanalytics.com/2008/12/use-equals-or-arrow-for-assignment.html
【讨论】:
两者都被使用,只是在不同的上下文中。如果我们不在正确的上下文中使用它们,我们会看到错误。见这里:
使用 是为了定义一个局部变量。
#Example: creating a vector
x <- c(1,2,3)
#Here we could use = and that would happen to work in this case.
使用 ,正如 Joshua Ulrich 所说,搜索父环境“寻找正在分配的变量的现有定义”。如果没有父环境包含该变量,它将分配给全局环境。
#Example: saving information calculated in a function
x <- list()
this.function <– function(data){
...misc calculations...
x[[1]] <<- result
}
#Here we can't use ==; that would not work.
使用 = 是为了说明我们如何在参数/函数中使用某些东西。
#Example: plotting an existing vector (defining it first)
first_col <- c(1,2,3)
second_col <- c(1,2,3)
plot(x=first_col, y=second_col)
#Example: plotting a vector within the scope of the function 'plot'
plot(x<-c(1,2,3), y<-c(1,2,3))
#The first case is preferable and can lead to fewer errors.
如果我们询问一件事是否等于另一件事,我们使用 ==,如下所示:
#Example: check if contents of x match those in y:
x <- c(1,2,3)
y <- c(1,2,3)
x==y
[1] TRUE TRUE TRUE
#Here we can't use <- or =; that would not work.
【讨论】:
<<- 是 not 用于分配给全局环境。它在父环境中搜索“正在分配的变量的现有定义”。它分配给全局环境的唯一时间是没有父环境包含该变量。