[英]Make a list of equal length vectors
在SO( LINK )的一个问题中,一张海报问了一个问题,我给出了一个有效的答案,但有一个部分让我烦恼,从矢量创建一个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)
编辑
这是一个有趣的方法,由Wojciech Sobala发布在与此相关的另一个帖子上(我要求他们在这里回答,如果他们这样做,我将删除此编辑)
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))
}
不确定这是否能完成这项工作?
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
}
编辑:将输出更改为列表
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
xx <- 1:10
xxr <- rle(0:(length(1:10)-1) %/% 3) # creates an rle object
fac3 <- rep( xxr$values[xxr$lengths == 3], each=3) #selects the one of length 3
# and recreates the shortened grouping vector
tapply(xx[ 1:length(fac3)], # a shortened original vector
fac3, list) # split into little lists
$`0` # Hope you don't mind having names on your list
[1] 1 2 3
$`1`
[1] 4 5 6
$`2`
[1] 7 8 9
它不是最短的,但这里有一个小的递归版本:
wrap <- function(n,x,lx,y) {
if (lx < n) return (y)
z <- x[-(1:n)]
wrap(n, z, length(z), c(y, list(x[1:n])))
}
wrapit <- function(x,n) {
wrap(n,x,length(x),list())
}
> wrapit(1:10,3)
[[1]]
[1] 1 2 3
[[2]]
[1] 4 5 6
[[3]]
[1] 7 8 9
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.