将 R 中的向量转换为嵌套列表
Convert a vector in R to a nested list
我有一个长度为 n 的向量,我想将它转换为嵌套列表。外部列表的长度应为 n / 2
,并且此列表中的每个项目都应有两个子列表。每个列表中的第一个子列表将包含向量中的奇数元素,第二个子列表将包含偶数元素(如果这没有意义,请参阅我的示例代码......我很难时间用一般术语描述它)。
问题: 有没有办法在不使用for循环的情况下将这个向量转换成嵌套列表?
我是在模拟环境中这样做的,所以我想确保它尽可能快。上述向量在模拟迭代之间的长度会有所不同,因此我试图找到一个可以概括为长度为 n 的向量的答案。向量将始终为 even though.
示例矢量和列表:
ex_vector <- 1:6
ex_list <- list(
list(1, 2),
list(3, 4),
list(5, 6)
)
编辑:修复了示例代码中的一个错误
我们用 gl
和 split
创建一个分组变量,将 vector
转换为 list
并用 as.list
list
n <- 2
out <- lapply(split(ex_vector, as.integer(gl(length(ex_vector), n,
length(ex_vector)))), as.list)
str(out)
#List of 3
# $ 1:List of 2
# ..$ : int 1
# ..$ : int 2
# $ 2:List of 2
# ..$ : int 3
# ..$ : int 4
# $ 3:List of 2
# ..$ : int 5
# ..$ : int 6
或使用%/%
到split
lapply(split(ex_vector, (seq_along(ex_vector)-1) %/% n + 1), as.list)
或紧凑
split(as.list(ex_vector), cumsum(seq_along(ex_vector) %%2))
n <- length(ex_vector)
lapply(split(ex_vector, rep(1:(n/2), each = 2)), split, 1:2)
我不确定是否理解一般原理,但下面的代码适用于该示例:
> x <- apply(matrix(ex_vector, ncol=2, byrow=TRUE), 1, as.list)
> str(x)
List of 3
$ :List of 2
..$ : int 1
..$ : int 2
$ :List of 2
..$ : int 3
..$ : int 4
$ :List of 2
..$ : int 5
..$ : int 6
我有一个长度为 n 的向量,我想将它转换为嵌套列表。外部列表的长度应为 n / 2
,并且此列表中的每个项目都应有两个子列表。每个列表中的第一个子列表将包含向量中的奇数元素,第二个子列表将包含偶数元素(如果这没有意义,请参阅我的示例代码......我很难时间用一般术语描述它)。
问题: 有没有办法在不使用for循环的情况下将这个向量转换成嵌套列表? 我是在模拟环境中这样做的,所以我想确保它尽可能快。上述向量在模拟迭代之间的长度会有所不同,因此我试图找到一个可以概括为长度为 n 的向量的答案。向量将始终为 even though.
示例矢量和列表:
ex_vector <- 1:6
ex_list <- list(
list(1, 2),
list(3, 4),
list(5, 6)
)
编辑:修复了示例代码中的一个错误
我们用 gl
和 split
创建一个分组变量,将 vector
转换为 list
并用 as.list
list
n <- 2
out <- lapply(split(ex_vector, as.integer(gl(length(ex_vector), n,
length(ex_vector)))), as.list)
str(out)
#List of 3
# $ 1:List of 2
# ..$ : int 1
# ..$ : int 2
# $ 2:List of 2
# ..$ : int 3
# ..$ : int 4
# $ 3:List of 2
# ..$ : int 5
# ..$ : int 6
或使用%/%
到split
lapply(split(ex_vector, (seq_along(ex_vector)-1) %/% n + 1), as.list)
或紧凑
split(as.list(ex_vector), cumsum(seq_along(ex_vector) %%2))
n <- length(ex_vector)
lapply(split(ex_vector, rep(1:(n/2), each = 2)), split, 1:2)
我不确定是否理解一般原理,但下面的代码适用于该示例:
> x <- apply(matrix(ex_vector, ncol=2, byrow=TRUE), 1, as.list)
> str(x)
List of 3
$ :List of 2
..$ : int 1
..$ : int 2
$ :List of 2
..$ : int 3
..$ : int 4
$ :List of 2
..$ : int 5
..$ : int 6