Search code examples
rloopsvectorseqrep

repeat a vector up to the nth element


The vector i want to repeat is :

> months2014
[1] "07" "08" "09" "10" "11" "12"

I want to repeat it based on this vector which defines the nth values:

> num_times
  [1]  6  6  6  6  5  6  6  5  6  6  6  6  6  6  6  6  6  6  6  6  6  6  6  6  6  6  6  6  6  6  6  6
 [33]  6  6  6  6  6  6  6  6  6  6  6  6  6  6  6  6  6 12  6  6  6  6  6  6  6 12  6  6  6  6  6  6
 [65]  6  6  6  6  6  6  6  6  6  6  6  6  6  6  6  6  6  6  6  6  6  6  6  6  6  6  6  6  6  6 12  6
 [97]  6  6 12  6  6  6  6  6  6  6  6 12  6  6  6  6  6  6  6  6  6  6  6  6  6  6  6  6  6  2  6  6
[129]  6 12  6  6  6  6  6  6

I used this loop to get the below output:

for (i in num_times)  
  print(months2014[1:i])

[1] "07" "08" "09" "10" "11" "12"
[1] "07" "08" "09" "10" "11" "12"
[1] "07" "08" "09" "10" "11" "12"
[1] "07" "08" "09" "10" "11" "12"
[1] "07" "08" "09" "10" "11" ## repeated upto the 5th element
[1] "07" "08" "09" "10" "11" "12"
[1] "07" "08" "09" "10" "11" "12"
[1] "07" "08" "09" "10" "11" ## repeated up to the 6th element

If you look at the num_times vector, it also has 12. Because of this I also get this result:

[1] "07" "08" "09" "10" "11" "12" NA   NA   NA   NA   NA   NA

There are only 6 elements in months2014 so I get NAs. I actually want it to restart and get output like this:

[1] "07" "08" "09" "10" "11" "12" "07   "08" "09"   "10"   "11"   "12"

I have three questions:

1) How do I save the loop output? I tried creating an empty vector and putting the results into it but that didn't work:

temp_vec <- c()
for (i in num_times)  
  temp_vec <- print(months2014[1:i])

2) How do I fix the NA ?

3) There must be a better way of doing this?


Solution

  • After testing this seems to work:

    sapply(num_times,function(x) rep(months2014,length.out=x)
    

    It outputs a list and repeats the sequence if the value in num_times is higher than the length of months214:

    [[1]]
    [1] "07" "08" "09" "10" "11" "12"
    
    [[2]]
    [1] "07" "08" "09" "10" "11" "12"
    
    [[3]]
    [1] "07" "08" "09" "10" "11" "12"
    
    [[4]]
    [1] "07" "08" "09" "10" "11" "12"
    
    [[5]]
    [1] "07" "08" "09" "10" "11"
    
    [[6]]
     [1] "07" "08" "09" "10" "11" "12" "07" "08" "09" "10" "11" "12"