首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >R打印for循环中列表的下一个元素

R打印for循环中列表的下一个元素
EN

Stack Overflow用户
提问于 2020-02-09 07:42:58
回答 1查看 185关注 0票数 1

我想打印瓶子歌(见https://en.wikipedia.org/wiki/Ten_Green_Bottles)。

我的循环代码如下所示:

代码语言:javascript
复制
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()

结果是这样的:

代码语言:javascript
复制
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 

..。(以此类推)

代码语言:javascript
复制
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”。我想你明白我的意思了。

这看起来并不难,但我就是找不到答案。你能帮帮我吗?谢谢!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-02-09 07:50:19

它可以循环遍历序列,然后根据索引提取值

代码语言:javascript
复制
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()
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60132269

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档