为什么Google的R风格指南推荐< - 用于分配,而不是=?

时间:2017-09-03 19:13:43

标签: r google-style-guide

我读了the Google style guide for R。对于“作业”,他们说:

  

使用< - ,not =进行作业。

     

GOOD:
  x < - 5

     

BAD:
  x = 5

你能告诉我这两种分配方法之间有什么区别,为什么一种方法比另一方更受欢迎?

2 个答案:

答案 0 :(得分:3)

我相信有两个原因。一个是<-=的含义略有不同,具体取决于具体情况。例如,比较语句的行为:

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

答案 1 :(得分:3)

两者都在不同的环境中使用。如果我们不在正确的背景下使用它们,我们会看到错误。见这里:

使用&lt; - 来定义局部变量。

./scripts/test.sh

使用&lt;&lt; - ,正如Joshua Ulrich所说,在父环境中“搜索已分配变量的现有定义”。如果没有父环境包含变量,它将分配给全局环境。

#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.
相关问题