我读the Google style guide for R。对于“分配”,他们说:为什么Google的R风格指南推荐< - 用于分配,而不是=?
使用< - ,not =,进行赋值。
GOOD:
X < - 5BAD:
X = 5
你能告诉我不同的是分配这两种方法是什么,为什么一个是要优先于其他?
我读the Google style guide for R。对于“分配”,他们说:为什么Google的R风格指南推荐< - 用于分配,而不是=?
使用< - ,not =,进行赋值。
GOOD:
X < - 5BAD:
X = 5
你能告诉我不同的是分配这两种方法是什么,为什么一个是要优先于其他?
我相信有两个原因。一个是<-
和=
根据上下文略有不同的含义。例如,比较的发言的行为:
printx <- function(x) print(x)
printx(x="hello")
printx(x<-"hello")
在第二种情况下,也printx(x<-"hello")
将分配给父范围,而printx(X =“你好”)将只设置参数。
另一个原因是历史的目的。 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.
使用< < -,约书亚乌尔里希说,搜索父环境“为赋值的变量的现有定义。”如果没有父环境包含变量,它将分配给全局环境。
#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.
'<< - '不是*用于分配给全球环境。它搜索父环境“以获取被分配的变量的现有定义。”只有在没有父环境包含变量的情况下,它才分配给全局环境。 –
一个一般的“规则”:问一个新问题之前搜索。我通过搜索“[r]作业”找到答案。 –
@CodyGray感谢编辑 - 这会好得多。 –