在一个关于SO的问题中(LINK https://stackoverflow.com/questions/10661295/apply-a-function-over-groups-of-columns)一个海报问了一个问题,我给出了一个有效的答案,但有一个部分让我烦恼,创建了一个list
从向量作为索引列表传递。所以说我有这个向量:
n <- 1:10
#> n
# [1] 1 2 3 4 5 6 7 8 9 10
假设我想将其分解为一个向量列表,每个向量的长度为 3。实现此目的的最佳(最短代码量和或最快)方法是什么?我们想扔掉第 10 项,因为它还剩下 1 (10 %% 3
)从 10/3 (length(n) - 10 %% 3
).
这就是想要的结果
list(1:3, 4:6, 7:9)
这将为我们提供那些不能组成三人组的索引:
(length(n) + 1 - 10 %% 3):length(n)
EDIT
这是 Wojciech Sobala 在其他线程 https://stackoverflow.com/questions/10661295/apply-a-function-over-groups-of-columns这是链接到的(我要求他们在这里回答,如果他们这样做,我将删除此编辑)
n <- 100
l <- 3
n2 <- n - (n %% l)
split(1:n2, rep(1:n2, each=l, length=n2))
作为一个函数:
indices <- function(n, l){
if(n > l) stop("n needs to be smaller than or equal to l")
n2 <- n - (n %% l)
cat("numbers", (n + 1 - n %% l):n, "did not make an index of length", l)
split(1:n2, rep(1:n2, each=l, length=n2))
}