【问题标题】:Why does Google's R style guide recommend <- for assignment, rather than =? [duplicate]为什么 Google 的 R 风格指南推荐 <- 用于赋值,而不是 =? [复制]
【发布时间】:2018-02-12 02:21:53
【问题描述】:

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

使用

好:
x

不好:
x = 5

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

【问题讨论】:

  • 一个通用的“规则”:在提出新问题之前进行搜索。我通过搜索“[r] assignment”找到了答案。
  • @CodyGray 感谢您的编辑 -- 这样好多了。
  • @samcarter 非常感谢。

标签: r google-style-guide


【解决方案1】:

我相信有两个原因。一是&lt;-= 的含义会根据上下文略有不同。例如,比较语句的行为:

printx <- function(x) print(x)
printx(x="hello")
printx(x<-"hello")

在第二种情况下,printx(x&lt;-"hello") 也会分配给父作用域,而 printx(x="hello") 只会设置参数。

另一个原因是出于历史目的。 R、S 和它们所基于的“APL”语言都只允许使用箭头键进行分配(历史上只有一个字符)。参考:http://blog.revolutionanalytics.com/2008/12/use-equals-or-arrow-for-assignment.html

【讨论】:

    【解决方案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.
    

    【讨论】:

    • &lt;&lt;-not 用于分配给全局环境。它在父环境中搜索“正在分配的变量的现有定义”。它分配给全局环境的唯一时间是没有父环境包含该变量。
    猜你喜欢
    • 1970-01-01
    • 2011-01-02
    • 2019-10-25
    • 1970-01-01
    • 1970-01-01
    • 2015-09-02
    • 2013-08-02
    • 1970-01-01
    • 2014-07-04
    相关资源
    最近更新 更多