我是R(并且通常编程)的新手,并且对于为什么下面的代码产生不同的结果感到困惑:
x <- 100
for(i in 1:5){
x <- x + 1
print(x)
}
Run Code Online (Sandbox Code Playgroud)
这会按照我的预期逐步打印序列101:105.
x <- 100
f <- function(){
x <- x + 1
print(x)
}
for(i in 1:5){
f()
}
Run Code Online (Sandbox Code Playgroud)
但这只打印了101次.
为什么将逻辑打包到函数中会导致它在每次迭代时恢复到原始值而不是递增?我能做些什么来使这项工作成为一个反复调用的功能?
jon*_*shf 15
这是因为在你的函数中,你正在处理x左侧的局部变量,以及x右侧的全局变量.您没有更新x函数中的全局,而是将值赋给101本地x.每次调用该函数时,都会发生相同的事情,因此您将local赋值x为1015次,并将其打印5次.
为了帮助可视化:
# this is the "global" scope
x <- 100
f <- function(){
# Get the "global" x which has value 100,
# add 1 to it, and store it in a new variable x.
x <- x + 1
# The new x has a value of 101
print(x)
}
Run Code Online (Sandbox Code Playgroud)
这将类似于以下代码:
y <- 100
f <- function(){
x <- y + 1
print(x)
}
Run Code Online (Sandbox Code Playgroud)
至于如何解决它.将变量作为参数,并将其作为更新传回.像这样的东西:
f <- function(old.x) {
new.x <- old.x + 1
print(new.x)
return(new.x)
}
Run Code Online (Sandbox Code Playgroud)
您可能希望存储返回值,因此更新后的代码如下所示:
x <- 100
f <- function(old.x) {
new.x <- old.x + 1
print(new.x)
return(new.x)
}
for (i in 1:5) {
x <- f(x)
}
Run Code Online (Sandbox Code Playgroud)