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

r打印for循环中列表的下一个元素,r,list,loops,R,List,Loops,我想打印瓶歌(请参阅) 我的循环代码如下所示: 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(nu

我想打印瓶歌(请参阅)

我的循环代码如下所示:

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()
。。。(等等)

因此,目前在每一段的最后一行写着“将有九个绿色的瓶子挂在墙上”(除了一个瓶子的段落)。我想要的是列表中的下一个数字,而不是总是“九”。 我想你明白我的意思了


这似乎并不难,但我就是找不到答案。。你能帮助我吗?谢谢

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

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()
库(stringr)

瓶子我想你可能需要在序列上循环

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 
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()