双重打印循环

时间:2019-02-06 01:41:40

标签: r loops for-loop

我只有一个列表

list <-c(“ hello”,“ my”,“ name”,“ is”,“ micky”,“。”)

如何在已有的代码内进行二级循环?

for(i in 1:12){
  print(c[i])
}

我正在寻找的是将输出打印为:

hello
hello my
hello my name
hello my name is
hello my name is micky
hello my name is micky.

1 个答案:

答案 0 :(得分:0)

你可以

vec<- c("hello", "my", "name", "is", "micky",".")

for(i in 1:length(vec)){
   for(j in 1:i) {
    cat(vec[j], " ")
   }
  cat("\n")
}

#hello  
#hello  my  
#hello  my  name  
#hello  my  name  is  
#hello  my  name  is  micky  
#hello  my  name  is  micky  .  

但是,您也可以这样做

sapply(seq_along(vec), function(x) paste0(vec[1:x], collapse = " "))

#[1] "hello"           "hello my"         "hello my name"           
#[4] "hello my name is"  "hello my name is micky"   "hello my name is micky ."