我正在阅读R语言手册,并想知道循环函数返回的值.Manuall在3.3.2循环中说:
三个语句[for,while,repeat]中的每一个都返回已评估的最后一个语句的值....循环语句返回的值始终为NULL并且以不可见的方式返回.
那么返回什么值,NULL或在循环中计算的最后一个语句的值?
此致,奥利弗
你在谈论这个:https://cran.r-project.org/doc/manuals/r-release/R-lang.html#Looping
x = for(i in 1:10){ i }
i
#[1] 10
x
#NULL
x <- while(i < 20){ i=i+1 }
i
#[1] 20
x
#NULL
x <- repeat { if(i>=30){break}; i=i+1 }
i
#[1] 30
x
#NULL
Run Code Online (Sandbox Code Playgroud)
非常肯定是NULL.
我检查了文档的旧版本.语句"循环语句语句返回的值总是@code {NULL}并且无形地返回." 首先出现在R3.0.0中(它不存在于2.9.0中).似乎行为发生了变化,文档可能没有得到充分清理.
jicawi@JimisPC:~$ diff R-lang.2.9.0.texi R-lang.3.0.0.texi > R-lang.diff
jicawi@JimisPC:~$ grep -n NULL R-lang.diff
82:> The value returned by a loop statement statement is always @code{NULL}
...
Run Code Online (Sandbox Code Playgroud)
所以,我安装了R 2.9.0并运行了同样的事情:
x = for(i in 1:10){ i }
x
#[1] 10
x <- while(i < 20){ i=i+1 }
x
#[1] 20
x <- repeat { if(i>=30){break}; i=i+1 }
x
#[1] 30
Run Code Online (Sandbox Code Playgroud)
绝对是最后一句话:)
提交的错误报告:https://bugs.r-project.org/bugzilla/show_bug.cgi?id = 16729
好眼力!