使用类似以下示例的代码:
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"
最佳答案
我们可以创建一个等于'x'长度的'0s'向量,使用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)))
关于r - R创建按索引划分的向量列表,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29990401/