在这里关于SO(LINK)的一个问题中,一张海报问了一个问题,我给出了一个有效的答案,但有一个部分让我烦恼,list从一个矢量创建一个传递作为索引列表.所以说我有这个载体:
n <- 1:10
#> n
# [1] 1 2 3 4 5 6 7 8 9 10
Run Code Online (Sandbox Code Playgroud)
假设我想将它分解为一个向量列表,每个向量的长度为3.什么是最好的(最短的代码量和/或最快的)方法来完成这个?我们想抛出第10项,因为10 %% 3从10/3(length(n) - 10 %% 3)开始有1()的余数.
这是期望的结果
list(1:3, 4:6, 7:9)
Run Code Online (Sandbox Code Playgroud)
这将为我们提供那些不能成为三个一组的指数:
(length(n) + 1 - 10 %% 3):length(n)
Run Code Online (Sandbox Code Playgroud)
编辑
这是一个有趣的方法,由Wojciech Sobala发布在与此相关的另一个帖子上(我要求他们在这里回答,如果他们这样做,我将删除此编辑)
n <- 100
l <- 3
n2 <- n - (n %% l)
split(1:n2, rep(1:n2, each=l, length=n2))
Run Code Online (Sandbox Code Playgroud)
作为一个功能:
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))
}
Run Code Online (Sandbox Code Playgroud)
不确定这是否能完成这项工作?
x = function(x, n){
if(n > x) stop("n needs to be smaller than or equal to x")
output = matrix(1:(x-x%%n), ncol=(x-x%%n)/n, byrow=FALSE)
output
}
Run Code Online (Sandbox Code Playgroud)
编辑:将输出更改为列表
x = function(x, n){
if(n > x) stop("n needs to be smaller than or equal to x")
output = matrix(1:(x-x%%n), ncol=(x-x%%n)/n, byrow=TRUE)
split(output, 1:nrow(output))
}
Example:
x(10, 3)
$`1`
[1] 1 2 3
$`2`
[1] 4 5 6
$`3`
[1] 7 8 9
Run Code Online (Sandbox Code Playgroud)