目前,我有
extract_modulo = function(x, n, fn=`[`) fn(x, (n-1L) %% length(x) + 1L)
`%[mod%` = function (x, n) extract_modulo(x, n)
然后:
seq(12) %[mod% 14
#[1] 2
这已经在某个地方内置了吗?我想是的,因为R有几个回收值的函数(例如paste
)。但是,我找不到help('[[')
,??index
或??mod
的任何内容。我认为对此的R符号可能类似于seq(12)[/14/]
或as.list(seq(12))[[/14/]]
。
答案 0 :(得分:0)
rep_len()
是一个快速.Internal
函数,适用于此用途或在您自己的函数中回收参数时。对于这种特殊情况,你在索引位置上寻找超出向量长度的值,rep_len(x, n)[n]
将总是做你想要的,对于任何非负整数'n',任何非NULL
x
。
rep_len(seq(12), 14)[14]
# [1] 2
rep_len(letters, 125)[125]
# [1] "u"
如果事实证明您不需要回收x
,那么n
的值小于length(x)
rep_len(seq(12), 5)[5]
# [1] 5
rep_len(seq(12), 0)[0]
# integer(0)
# as would be expected, there is nothing there
如果你愿意,你当然可以创建一个包装器:
recycle_index <- function(x, n) rep_len(x, n)[n]
recycle_index(seq(12), 14)
# [1] 2