R按索引创建分割矢量列表

时间:2015-05-01 15:57:13

标签: r vector grouping

使用此示例的代码:

set.seed(11)
x <- sample(letters)
x
 [1] "h" "a" "m" "y" "b" "u" "v" "f" "p" "c" "q" "g" "x" "l" "i" "o" "e" "r" "t" "d" "z" "k" "s" "j" "w" "n"

并提供了这个值向量

y <- c(4, 13, 20)

我想将x向量分割为y向量作为'切片'索引。并将结果分组为列表。期望的输出:

z <- list(c("h", "a", "m", "y"),c("b", "u", "v", "f", "p", "c", "q", "g", "x"), c("l", "i", "o", "e", "r", "t", "d"), c("z", "k", "s", "j", "w", "n") )
z
[[1]]
[1] "h" "a" "m" "y"

[[2]]
[1] "b" "u" "v" "f" "p" "c" "q" "g" "x"

[[3]]
[1] "l" "i" "o" "e" "r" "t" "d"

[[4]]
[1] "z" "k" "s" "j" "w" "n"

1 个答案:

答案 0 :(得分:3)

我们可以创建一个'0'的矢量等于'x'的长度,使用y作为数字索引,将v1中的元素替换为1,cumsum结果和用作分组矢量来分割'x'

v1 <- numeric(length(x))
v1[y+1] <- 1
split(x,cumsum(v1))

或者我们可以通过对cumsum的结果tabulate获取分组向量

 split(x,cumsum(tabulate(y+1, length(x))))

或使用match

split(x,cumsum(c(TRUE,!is.na(match(seq_along(x), y)[-length(x)]))))

%in%

 split(x,cumsum(seq_along(x) %in% (y+1)))