【问题标题】:the difference between = and <- operator in the function system.time()函数system.time()中=和<-操作符的区别
【发布时间】:2012-11-19 17:04:17
【问题描述】:

我正在使用函数 system.time() 并且我发现了一些令我惊讶的东西。我经常使用分配符号“=”而不是“

代码如下:

a = matrix(1, nrow = 10000)

require(stats)
system.time(a[,1] = a[,1]*2) #this line doesn't work 
#Error: unexpected '=' in "system.time(a[,1] ="
system.time(a[,1] = a[,1]*2) #this line works
system.time(for(i in 1:100){a[,1] = a[,1]*i}) #this line works!!!!

我发现:Is there a technical difference between "=" and "<-" 解释了我不能在函数中使用“=”进行分配,因为它是在函数中分配参数的符号。但我惊讶地发现它有时可以工作(见下面的代码)。

有谁知道它为什么在这里工作? (也是为什么它在第一种情况下不起作用,因为我猜 a[,1] 不是函数 system.time()...的参数...)

非常感谢。 埃德温。

【问题讨论】:

  • 这已经被问过了。您的代码是有效的,因为它包含在 { ... }

标签: r assignment-operator


【解决方案1】:

将您的代码包装在{ ... } 大括号中,它将起作用:

system.time({a[,1] = a[,1]*2})
   user  system elapsed 
      0       0       0 

来自?"&lt;-"

运算符

【讨论】:

  • 这对我来说听起来更奇怪。我现在就用这个​​方法,谢谢。这是为什么?有谁知道“{ ... }”使代码工作的原因吗?谢谢
  • 这是因为您告诉解析器您希望它为对象分配值,而不是创建一个列表以传递给函数。
  • 或者最好开始使用&lt;- 进行分配!
【解决方案2】:

system.time(a[,1] = a[,1]*2) 中,等号并不意味着赋值,它被解释为试图绑定一个“命名参数”;但system.time 没有该名称的参数。

system.time(for(i in 1:100){a[,1] = a[,1]*i}) 中,等号确实是在做赋值;而且效果很好。

如果你写了system.time(a[,1] &lt;- a[,1]*2) &lt;- 只能表示赋值,而不是参数绑定,它可以工作!

但要小心!如果您写了system.time(a[,1] &lt; - a[,1]*2),它也“有效”,但可能与您的意思不符!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-04-18
    • 1970-01-01
    • 2011-02-19
    • 2011-06-10
    • 1970-01-01
    • 1970-01-01
    • 2016-03-17
    • 2023-03-17
    相关资源
    最近更新 更多