Is there an elegant, built-in modulo indexing method in R?

I currently have

extract_modulo = function(x, n, fn=`[`) fn(x, (n-1L) %% length(x) + 1L) `%[mod%` = function (x, n) extract_modulo(x, n) 

And then:

 seq(12) %[mod% 14 #[1] 2 

Is it already built into R? I would think so, because R has several functions that process values ​​(like paste ). However, I do not find anything with help('[[') , ??index or ??mod . I would think that the notation R for this would look, for example, as seq(12)[/14/] or as.list(seq(12))[[/14/]] .

+7
r indexing builtin mod
source share
1 answer

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] # [1] 2 rep_len(letters, 125)[125] # [1] "u" 

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] # [1] 5 rep_len(seq(12), 0)[0] # integer(0) # as would be expected, there is nothing there 

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) # [1] 2 
0
source share

All Articles