我阅读了有关R的Google样式指南。"分配",他们说:
使用< - ,不=,用于分配。
好:
x< - 5坏:
x = 5
您能告诉我这两种分配方法之间有什么区别,为什么要优先于另一个?
我相信有两个原因。一个是<-
和=
取决于上下文的含义略有不同。例如,比较语句的行为:
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-equals-erow-for-assignment.html
两者都在不同的上下文中使用。如果我们不在正确的上下文中使用它们,我们会看到错误。请参阅此处:
使用&lt; - 用于定义本地变量。
#Example: creating a vector
x <- c(1,2,3)
#Here we could use = and that would happen to work in this case.
使用&lt;&lt; - ,正如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.