-5

我阅读了 R 的 Google 风格指南。对于“作业”,他们说:

使用 <-,而不是 =,进行赋值。

好:
x <- 5

不好:
x = 5

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

4

2 回答 2

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

于 2017-09-03T19:23:30.387 回答
2

两者都被使用,只是在不同的上下文中。如果我们不在正确的上下文中使用它们,我们会看到错误。看这里:

使用<-用于定义局部变量。

#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.
于 2017-09-03T19:24:57.360 回答