Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/variables/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何定义';本地';R中的变量?_R_Variables_Scope_Local - Fatal编程技术网

如何定义';本地';R中的变量?

如何定义';本地';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 或者,您可以避免循环

例如,在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

或者,您可以避免循环,使用
*apply
和/或通过设计使用局部变量的函数。参见示例

函数中的任何内容都是局部的,因此最好使用函数而不是循环,或者可能使用
local
?@NelsonGon据我所知,R没有像python那样的
local
(我刚刚在for循环中定义变量时尝试使用该前缀,它没有wokr)我很少用R写显式循环,你能添加一些例子吗?参见备选方案。这使用了
local
,但随后一切都是
local
number@NelsonGon哦,我不知道一个人可以像接受的答案中那样从for循环中找到答案。
 for(i in number){
  res2 <-res[i] + 42
  print(res2)
 }