回收负向和正向的字符向量

时间:2017-08-15 06:32:43

标签: r vector

我有字符,字母和符号的矢量:

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

我想构建一个可以回收向量recycle的函数vec,以便recycle(vec, 68)类似于vec[68]'a')和recycle(vec, -1)'&'

3 个答案:

答案 0 :(得分:4)

矢量化解决方案:

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)

已编辑以不为索引= 0返回任何内容。

答案 1 :(得分:1)

这可能是一种简单的方法:

recycle <- function( vec , x ){
  l <- length(vec)   
  #  Deal with negative indices
  if( x < 0 ){
    vec <- rev(vec)
    x <- abs(x)
  }
  #  Extend vector if required index is longer
  if( x > l ){
    t <- x %/% l + 1
    vec <- rep( vec , t )
  }
  # Get value
  vec[x]
}

给出了:

recycle (vec,68)
#[1] "a"

recycle(vec,-1)
#[1] "&"

recycle(vec,0)
#character(0)

答案 2 :(得分:0)

我们可以使用%%

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

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

它也可以使用空数或负数,但是它与你的要求相比有一个偏差:

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

所以让我们调整它并处理0值:

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"