如何将索引保持在向量范围内?

Joh*_*nry 1 r

如何循环索引向量?

我有一个数字向量。我想一次索引这个向量(例如,i[1]、i[2] ...)。但是,在index_n > length(i)我希望索引再次“循环”回到向量之后。

i = c("cat", "dog", "ghost")
i[4] # 4 is 1 greater than than the length of the vector, i want to return the first element "cat"
## > NA
Run Code Online (Sandbox Code Playgroud)

有很多方法可以用逻辑语句来做到这一点。我想知道是否已经有一个功能可以做到这一点。

MrF*_*ick 5

没有内置函数,但您可以编写自己的函数

looper <- function(x, i) {
   x[ (i-1) %% length(x) + 1 ]
}

i <- c("cat", "dog", "ghost")
looper(i, 3)
# [1] "ghost"
looper(i, 4)
# [1] "cat"
looper(i, 10)
# [1] "cat"
looper(i, 11)
# [1] "dog"
Run Code Online (Sandbox Code Playgroud)

这也适用于索引向量

looper(i, 1:7)
# [1] "cat"   "dog"   "ghost" "cat"   "dog"   "ghost" "cat"  
Run Code Online (Sandbox Code Playgroud)

如果你真的想要花哨,你可以创建一个类并覆盖它的索引函数。例如

`[.looper` <- function(x, i) {
    x <- unclass(x)
    x[ (i-1) %% length(x) + 1 ]
}
make_looper <- function(x) {
    class(x) <- "looper"
    x
}
Run Code Online (Sandbox Code Playgroud)

那么你可以做

x <- make_looper(i)
x[1]
# [1] "cat"
x[2]
# [1] "dog"
x[3]
# [1] "ghost"
x[4]
# [1] "cat"
Run Code Online (Sandbox Code Playgroud)

  • @r2evans 实际上,这是一个有趣的问题。我想知道有多少人依赖在正常范围之外索引时返回的隐式 NA 值。我想更容易混淆的部分不是提取值,而是分配它们。我猜想人们更有可能分配不存在的值,目的是添加新值而不是替换现有值。 (2认同)