如何定义';本地';R中的变量?
例如,在For循环中,我想定义一些变量来执行某些操作,但我想在迭代结束后自动删除它们如何定义';本地';R中的变量?,r,variables,scope,local,R,Variables,Scope,Local,例如,在For循环中,我想定义一些变量来执行某些操作,但我想在迭代结束后自动删除它们 但是,如果我使用将一个值分配给一个变量,那么这个答案说明了local在R中的循环中的用法: number <- 1:5 res <- numeric(5) local(for(i in number){ res2 <-res[i] + 42 print(res2) }) [1] 42 [1] 42 [1] 42 [1] 42 [1] 42 或者,您可以避免循环
但是,如果我使用
将一个值分配给一个变量,那么这个答案说明了local
在R中的循环中的用法:
number <- 1:5
res <- numeric(5)
local(for(i in number){
res2 <-res[i] + 42
print(res2)
})
[1] 42
[1] 42
[1] 42
[1] 42
[1] 42
或者,您可以避免循环,使用*apply
和/或通过设计使用局部变量的函数。参见示例函数中的任何内容都是局部的,因此最好使用函数而不是循环,或者可能使用local
?@NelsonGon据我所知,R没有像python那样的local
(我刚刚在for循环中定义变量时尝试使用该前缀,它没有wokr)我很少用R写显式循环,你能添加一些例子吗?参见备选方案。这使用了local
,但随后一切都是local
:number@NelsonGon哦,我不知道一个人可以像接受的答案中那样从for循环中找到答案。
for(i in number){
res2 <-res[i] + 42
print(res2)
}