根据R中另一个向量中定义的数字位置查找向量的元素

Finding elements of a vector based on the numerical positions defined in another vector in R

假设我有以下两个向量。 ll定义集合中元素的个数和分界线long

比如这里在ll的基础上,long中的前两个元素是一个单独的集合,那么后面的一个元素是一个单独的集合,依此类推。

我想知道如何根据 ll 自动(可能作为 sapply)子集 long 中的每个集合?

ll <- c(2, 1, 2, 3)
long <- c(F, F, F, F, T, T, F, T)

您可以使用 splitrep(seq_along(ll), ll) 拆分(输出 1 1 2 3 3 4 4 4)。

split(long, rep(seq_along(ll), ll))

$`1`
[1] FALSE FALSE

$`2`
[1] FALSE

$`3`
[1] FALSE  TRUE

$`4`
[1]  TRUE FALSE  TRUE