Search code examples
rvectornumericrecycle

R, function that turns numeric input into a recycled numeric output bounded by a upper limit


How can I write a function f(v, n) (or use a base R function) that turns a numeric vector v into another based on n, a recycling factor (in lack of a better word). For instance:

f(v = c(1,2,3,4,5), n = 1) #would yield c(1,2,3,4,5)
f(v = c(1,2,3,4,5), n = 2) #would yield c(1,2,1,2,1)
f(v = c(1,2,3,4,5), n = 3) #would yield c(1,2,3,1,2)
f(v = c(5,4,3,2,1), n = 3) #would yield c(2,1,3,2,1)
f(v = c(3,6), n = 3) #would yield c(3,3)

The closest I got was to use %%

1:5%%3 #giving me: [1] 1 2 0 1 2 - not quite what I want, at least some recycling.

Solution

  • We can create the function as

    f <- function(x, n) if(n ==1) x else (x - 1) %% n + 1
    f(1:5, 1)
    #[1] 1 2 3 4 5
    f(1:5, 2)
    #[1] 1 2 1 2 1
    
    f(1:5, 3)
    #[1] 1 2 3 1 2
    
    f(5:1, 3)
    #[1] 2 1 3 2 1
    
    f(c(3, 6), 3)
    #[1] 3 3