Recycle a vector of characters in negative and positive direction

Viewed 81

I have vector of characters, letters and symbols:

vec <-c(letters, 0:9, LETTERS, c("!","§","$","%","&"))

I would like to build a function recycle that can recycle the vector vec so that recycle(vec, 68) would be similar to vec[68] (an 'a') and recycle(vec, -1) would give an '&'.

3 Answers

We can use %%:

recycle0 <- function(vec,x) vec[[((x-1) %% length(vec))+1]]

recycle0(vec,1)  # [1] "a"
recycle0(vec,68) # [1] "a"
recycle0(vec,67) # [1] "&"

it works with null or negative numbers too but then it's offset by one compare to what you ask:

recycle0(vec,0)   # [1] "&"
recycle0(vec,-1)  # [1] "%"

so let's adapt it and deal with the 0 value:

recycle <- function(vec,x) if(!x) NA else vec[[((x - sign(x)/2 -0.5) %% length(vec))+1]]

recycle(vec,1)  # [1] "a"
recycle(vec,68) # [1] "a"
recycle(vec,67) # [1] "&"
recycle(vec,-1) # [1] "&"
recycle(vec,0)  # [1] "NA"
Related