r - Recycle a vector of characters in negative and positive direction -


lets have vector of characters, letters , symbols

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

i build function recycle can recycle vector vec recycle(vec, 68) similar vec[68] (an a) , recycle(vec, -1) give &.

a vectorized solution:

recycle <- function(vec, i) {   l <- length(vec)   ind <- (abs(i) - 1) %% l + 1   res <- ifelse(i > 0, vec[ind], vec[l - ind + 1])   res[i != 0] }  > print(recycle(vec, 68)) [1] "a" > print(recycle(vec, -1)) [1] "&" > print(recycle(vec, setdiff(-68:68, 0)))   [1] "&" "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p" "q" "r" "s" "t"  [22] "u" "v" "w" "x" "y" "z" "0" "1" "2" "3" "4" "5" "6" "7" "8" "9" "a" "b" "c" "d" "e"  [43] "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p" "q" "r" "s" "t" "u" "v" "w" "x" "y" "z"  [64] "!" "§" "$" "%" "&" "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p"  [85] "q" "r" "s" "t" "u" "v" "w" "x" "y" "z" "0" "1" "2" "3" "4" "5" "6" "7" "8" "9" "a" [106] "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p" "q" "r" "s" "t" "u" "v" [127] "w" "x" "y" "z" "!" "§" "$" "%" "&" "a" > all.equal(recycle(vec, setdiff(-68:68, 0)), recycle(vec, -68:68)) [1] true > recycle(vec, 0) character(0) 

edited return nothing index = 0.


Comments

Popular posts from this blog

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

python Tkinter Capturing keyboard events save as one single string -

sql server - Why does Linq-to-SQL add unnecessary COUNT()? -