使用此示例的代码:
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"
答案 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)))