我想打印瓶子歌(见https://en.wikipedia.org/wiki/Ten_Green_Bottles)。
我的循环代码如下所示:
number <- c("Ten", "Nine", "Eight", "Seven", "Six", "Five", "Four", "Three", "Two")
and_if <- ("And if one green bottle should accidentally fall,")
bottles <- function() {
for (num in number) {
cat(str_c(rep(num, 2), " green bottles hanging on the wall", collapse = "\n"), "\n", and_if, "\n", "There'll be", number[2], "green bottles hanging on the wall", "\n", "\n")
if (num == "Two") {
cat(str_c(rep("One green bottle hanging on the wall", 2), collapse = "\n"), "\n", and_if, "\n", "There'll be no green bottles hanging on the wall", "\n", "\n")
}
}
}
bottles()结果是这样的:
Ten green bottles hanging on the wall
Ten green bottles hanging on the wall
And if one green bottle should accidentially fall,
There'll be Nine green bottles hanging on the wall
Nine green bottles hanging on the wall
Nine green bottles hanging on the wall
And if one green bottle should accidentially fall,
There'll be Nine green bottles hanging on the wall
Eight green bottles hanging on the wall
Eight green bottles hanging on the wall
And if one green bottle should accidentially fall,
There'll be Nine green bottles hanging on the wall ..。(以此类推)
One green bottle hanging on the wall
One green bottle hanging on the wall
and if one green bottle should accidentally fall,
There'll be no green bottles hanging on the wall 所以现在在每一段的最后一行写着“墙上将挂着九个绿色瓶子”(除了一个瓶子段落)。我希望打印列表中的下一个数字,而不是总是打印“9”。我想你明白我的意思了。
这看起来并不难,但我就是找不到答案。你能帮帮我吗?谢谢!
发布于 2020-02-09 07:50:19
它可以循环遍历序列,然后根据索引提取值
library(stringr)
bottles <- function() {
for (i in seq_along(number)) {
cat(str_c(rep(number[i], 2), " green bottles hanging on the wall", collapse = "\n"), "\n", and_if, "\n", "There'll be", replace(number[i+1], is.na(number[i+1]), "no"), "green bottles hanging on the wall", "\n", "\n")
if (i == length(number)) {
cat(str_c(rep("One green bottle hanging on the wall", 2), collapse = "\n"), "\n", and_if, "\n", "There'll be no green bottles hanging on the wall", "\n", "\n")
}
}
}
bottles()https://stackoverflow.com/questions/60132269
复制相似问题