R 将向量拆分为相同长度的子对象,并将每个子对象指定给一个新向量

R 将向量拆分为相同长度的子对象,并将每个子对象指定给一个新向量,r,R,假设我有一个向量,如下所示: s <- c(1:30) ## here the numbers are just an example. I just need to split it into the same length subvectors. 我想用lappy来实现这一点,因为有时我需要将向量拆分为10,3,或者任意数量的子向量取决于我的数据 我们可以使用gl创建的分组索引拆分向量。输出将是一个列表,最好将其保存在列表中,而不是全局环境中的多个对象 lst <- spli

假设我有一个向量,如下所示:

s <- c(1:30) ## here the numbers are just an example. I just need to split it into the same length subvectors. 

我想用
lappy
来实现这一点,因为有时我需要将向量拆分为
10
3
,或者任意数量的子向量取决于我的数据

我们可以
使用
gl
创建的分组索引拆分
向量。输出将是一个
列表
,最好将其保存在
列表
中,而不是全局环境中的多个对象

lst <- split(s, as.integer(gl(length(s), 10, length(s))))

当用
gl
的输出拆分“s”时,“s”的前10个值被分组在一起,然后是第二个10,依此类推。这些存储为
向量
s

列表
,您能给我解释一下
gl
的作用吗?@Maryam我更新了一些描述。希望有帮助\t尝试
split(s,sort(s%%3))
。。
  > s1
 [1]  1  2  3  4  5  6  7  8  9 10

> s2
 [1] 11 12 13 14 15 16 17 18 19 20

> s3
 [1] 21 22 23 24 25 26 27 28 29 30
lst <- split(s, as.integer(gl(length(s), 10, length(s))))
as.integer(gl(length(s), 10, length(s)))
#[1] 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3 3 3 3 3 3 3 3 3