制作等长向量的列表

2024-03-03

在一个关于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))
}

不确定这是否有效?

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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

制作等长向量的列表 的相关文章

随机推荐