gpt4 book ai didi

r - system.time()函数中=和<-运算符的区别

转载 作者:行者123 更新时间:2023-12-02 22:22:40 24 4
gpt4 key购买 nike

我正在使用函数 system.time(),我发现了一些让我吃惊的东西。我经常使用分配符号“=”而不是“<-”。我知道大多数 R 用户使用“<-”,但我认为“=”在我的代码中更清晰。因此,我使用“=”在函数 system.line() 中分配一个值,并出现以下错误消息:Error: unexpected '=' in "system.time(a[,1] ="

代码如下:

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() 的参数...)

非常感谢。埃德温。

最佳答案

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

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

来自 ?"<-"

The operators <- and = assign into the environment in which they are evaluated. The operator <- can be used anywhere, whereas the operator = is only allowed at the top level (e.g., in the complete expression typed at the command prompt) or as one of the subexpressions in a braced list of expressions.

关于r - system.time()函数中=和<-运算符的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13458653/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com