gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 11:04:36 25 4
gpt4 key购买 nike

像这个例子的代码:

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)

我想通过 y 向量将 x 向量拆分为“切片”索引。并将结果分组为列表。期望的输出:

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”长度的“0”向量,使用y作为数字索引,将v1中的元素替换为1 , cumsum 结果并将其用作分组向量以拆分 'x'

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

或者我们可以通过对 tabulate 的结果执行 cumsum 来获得分组向量

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

或者使用匹配

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按索引创建分割向量列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29990401/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com