如何获取向量的所有连续子集?

时间:2018-01-13 14:38:04

标签: r subset

如果我想获得矢量的所有子集,我可以例如使用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"}

2 个答案:

答案 0 :(得分:15)

请尝试Traceback (most recent call last): File "...", line 74, in <module> main() File "...", line 53, in main for doc in docs: File "/usr/lib/python2.7/site-packages/google/cloud/firestore_v1beta1/query.py", line 588, in get for index, response_pb in enumerate(response_iterator): File "/usr/lib/python2.7/site-packages/grpc/_channel.py", line 347, in next return self._next() File "/usr/lib/python2.7/site-packages/grpc/_channel.py", line 338, in _next raise self grpc._channel._Rendezvous: <_Rendezvous of RPC that terminated with (StatusCode.DEADLINE_EXCEEDED, Deadline Exceeded)> ,如下所示:

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))))

答案 1 :(得分:10)

base R选项为embed

lapply(seq_along(v), function(i) embed(v, i)[, i:1, drop = FALSE])
#[[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"