R 列出等长向量
在SO()上的一个问题中,一张海报问了一个问题,我给出了一个有效的答案,但有一部分让我感到困扰,从向量创建一个R 列出等长向量,r,R,在SO()上的一个问题中,一张海报问了一个问题,我给出了一个有效的答案,但有一部分让我感到困扰,从向量创建一个列表,作为索引列表传递。所以les说我有这个向量: n <- 1:10 #> n # [1] 1 2 3 4 5 6 7 8 9 10 这将为我们提供那些无法组成三人小组的指标: (length(n) + 1 - 10 %% 3):length(n) 编辑 以下是Wojciech Sobala在“这是链接到的”网站上发布的一个有趣的方法(我请他们在这里回
列表
,作为索引列表传递。所以les说我有这个向量:
n <- 1:10
#> n
# [1] 1 2 3 4 5 6 7 8 9 10
这将为我们提供那些无法组成三人小组的指标:
(length(n) + 1 - 10 %% 3):length(n)
编辑
以下是Wojciech Sobala在“这是链接到的”网站上发布的一个有趣的方法(我请他们在这里回答,如果他们回答,我将删除此编辑)
n不确定这是否起作用
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它不是最短的,但这里有一个小的递归版本:
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
wrap我没有编辑你的回复,只是把我的编辑放错了地方,抱歉+1但这不是一个列表,所以在海报的问题中它不起作用,除非你用数据包装输出。frame
@Tylerlinker:我把输出改成了一个列表。所有答案都很好,但我认为X是最短的代码。谢谢,这让我很烦。所有的方法都比我做的好得多。哇,这一个伤了我的面+1我甚至不知道理解递归函数是如何工作的(尽管索引的顺序是相反的),有时用纸和笔跟随函数调用链会有所帮助。或者在那里放一些打印语句来观察列表的增长和向量的收缩。
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