gpt4 book ai didi

r - 如何获得向量的所有连续子集?

转载 作者:行者123 更新时间:2023-12-03 23:21:31 25 4
gpt4 key购买 nike

如果我想获得向量的所有子集,我可以例如使用sets包:

library(sets)
v <- c("test1", "test2", "test3", "test4")
set_power(v)
## {{}, {"test1"}, {"test2"}, {"test3"}, {"test4"}, {"test1",
## "test2"}, {"test1", "test3"}, {"test1", "test4"}, {"test2",
## "test3"}, {"test2", "test4"}, {"test3", "test4"}, {"test1",
## "test2", "test3"}, {"test1", "test2", "test4"}, {"test1",
## "test3", "test4"}, {"test2", "test3", "test4"}, {"test1",
## "test2", "test3", "test4"}}


我的问题
如何仅获取所有元素都是连续的所有子集,因此在上述情况下没有 {"test1", "test3"}, {"test1", "test4"}, {"test2", "test4"}, {"test1", "test2", "test4"}, {"test1", "test3", "test4"}

最佳答案

像这样尝试rollapply

library(zoo)
v <- c("test1", "test2", "test3", "test4")

L <- lapply(seq_along(v), rollapply, data = v, c)
L[[1]] <- matrix(L[[1]])


提供 length(v)组件,每个子集大小一个:

[[1]]
[,1]
[1,] "test1"
[2,] "test2"
[3,] "test3"
[4,] "test4"

[[2]]
[,1] [,2]
[1,] "test1" "test2"
[2,] "test2" "test3"
[3,] "test3" "test4"

[[3]]
[,1] [,2] [,3]
[1,] "test1" "test2" "test3"
[2,] "test2" "test3" "test4"

[[4]]
[,1] [,2] [,3] [,4]
[1,] "test1" "test2" "test3" "test4"


或作为一个平面列表,每个子集包含一个组件:

flat <- do.call("c", lapply(L, function(x) split(x, 1:nrow(x))))


给予:

> str(flat)
List of 10
$ 1: chr "test1"
$ 2: chr "test2"
$ 3: chr "test3"
$ 4: chr "test4"
$ 1: chr [1:2] "test1" "test2"
$ 2: chr [1:2] "test2" "test3"
$ 3: chr [1:2] "test3" "test4"
$ 1: chr [1:3] "test1" "test2" "test3"
$ 2: chr [1:3] "test2" "test3" "test4"
$ 1: chr [1:4] "test1" "test2" "test3" "test4"

关于r - 如何获得向量的所有连续子集?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48240868/

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