具有原始向量所有不同值的最小子向量

时间:2018-11-15 10:30:55

标签: r vector

假设我们有一个长度为 n 的向量,其中 k 个不同的值。

{1, 4, 2, 2, 3, 4, 1, 1, 5, 2, 2}

我如何找出保留的各个元素的值,序列和频率的最小子集(在原始向量上)的开始和结束坐标,该值具有原始向量的所有不同值?

在我们的示例中,子集为

{2, 3, 4, 1, 1, 5}

,起始和结束坐标分别为49

1 个答案:

答案 0 :(得分:1)

这是将要执行的任务:首先,我创建一个向量index,其中index[k]等于要遍历的索引数量(从k开始)元素至少一次,如果不是这样,则等于Inf

# determining the unique elements of v
uniqueVals <- unique(v)
index <- numeric(length(v))

# helper function
myFun <- function(k){
   helper <- vapply(seq(k, length(v)), 
                    function(s) length(setdiff(uniqueVals, v[k:s])), 
                    numeric(1))
   return (ifelse(min(helper) == 0, which.min(helper)-1, Inf))
}

# indices in seq1 must be infinity as there are not enough values left
seq1 <- which(length(v) - seq_along(v) < length(uniqueVals))
index[seq1] <- Inf
# for the other indices we now use our helper function
index[seq(1, min(seq1)-1)] <- vapply(seq(1, min(seq1)-1), myFun, numeric(1)) 

# applying the above
startIndex <- which.min(index) 
endIndex <- index[startIndex] + startIndex
v[startIndex:endIndex]
# yielding
[1] 2 3 4 1 1 5

其中v = c(1, 4, 2, 2, 3, 4, 1, 1, 5, 2, 2)和任何给定的k myFun将返回最小的数字n,以使v[k:n]包含v的每个元素。