如何循环索引向量?
我有一个数字向量。我想一次索引这个向量(例如,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)
有很多方法可以用逻辑语句来做到这一点。我想知道是否已经有一个功能可以做到这一点。
没有内置函数,但您可以编写自己的函数
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)
| 归档时间: |
|
| 查看次数: |
34 次 |
| 最近记录: |