Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/jsp/3.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_For Loop - Fatal编程技术网

为什么R中的循环会重复多次?

为什么R中的循环会重复多次?,r,for-loop,R,For Loop,我正在复习我的迭代,在R for Data Science()中做一些for循环练习。我写这篇文章是为了模仿“墙上99瓶啤酒”: number如注释所示,这将重复100次,因为您忘记在循环中索引number。你不是说 for (i in number) { print(paste(number[99-i], "bottles of beer on the wall")) } 我想你应该在循环中使用I,而不是number number <- 99:0 for (i in number)

我正在复习我的迭代,在R for Data Science()中做一些for循环练习。我写这篇文章是为了模仿“墙上99瓶啤酒”:


number如注释所示,这将重复100次,因为您忘记在循环中索引number。你不是说

for (i in number) {
  print(paste(number[99-i], "bottles of beer on the wall"))
}

我想你应该在循环中使用
I
,而不是
number

number <- 99:0
for (i in number) {
 print(paste(i, "bottles of beer on the wall"))
}
numberedit:@bobbel第一名:-)

您需要在循环中
打印(i)
,而不是
打印(数字)
。后者是所有数字的向量,因此会重复很多次

[1] "5 bottles of beer on the wall"
[1] "4 bottles of beer on the wall"
[1] "3 bottles of beer on the wall"
[1] "2 bottles of beer on the wall"
[1] "1 bottles of beer on the wall"
密码
number如果您想要更简洁的版本,请使用
map\u dbl()
from
purrr

map_dbl(99:1,print(paste(99:1,'bottles of beer on the wall')))

这确实会返回一个错误:
错误:结果1不是长度为1的原子向量
,但您肯定会得到99次重复次数的倒计时

你是说我刚才看到你的错误,你需要改成:
print(把啤酒瓶贴在墙上)
。因为你想打印你当前的索引
i
。我知道这是一个练习,但我无法抗拒:-)
sprintf(%i瓶啤酒在墙上,99:0)
cat(sprintf(%i瓶啤酒在墙上,99:0))
没有循环(好吧,这是一个隐式循环)。@Uwe必须查找
sprintf
。看起来它是一个C函数,所以如果你不懂C,就没什么帮助了,对吧?@BenG No,
sprintf()
是一个基本的R函数。也许“借用”了C.有趣的方法,但有两条建议:1)在代码中使用硬编码的“幻数”通常是不好的做法,因为它们很容易破碎;2)此代码在第一行打印“墙上的啤酒瓶”
。一个可能的改进是
打印(粘贴(max(number)-i,“墙上的啤酒瓶”)
。你赢了我!:-)不完全是罗曼,你得到了答案。实际上,我的评论是第一条:-)
number <- 5:1
for (i in number) {
    print(paste(i, "bottles of beer on the wall"))
}
map_dbl(99:1,print(paste(99:1,'bottles of beer on the wall')))