rep_len() is a fast .Internal function and is suitable for this use or when reusing arguments in your own function. In this particular case, when you look for a value at an index position outside the length of the vector, rep_len(x, n)[n] will always do what you are looking for for any non-negative integer "n" and any non- NULL x .
rep_len(seq(12), 14)[14]
And if it turns out that you donβt need to recycle x , it works as well as a value of n that is less than length(x)
rep_len(seq(12), 5)[5]
Of course, you can create a wrapper if you want:
recycle_index <- function(x, n) rep_len(x, n)[n] recycle_index(seq(12), 14)
Dan hall
source share