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

标签 r vector

假设我们有一个长度为 n 且具有 k 个不同值的向量。

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

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

对于我们的示例,子集将是
{2, 3, 4, 1, 1, 5}

开始和结束坐标将为 49 , 分别。

最佳答案

这里有一些可以完成这个任务的东西:首先我创建一个向量 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 的每个元素.

关于r - 具有原始向量的所有不同值的最小子向量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53317387/

相关文章:

r - 不同数据类型的bind_rows

R:累计统计该列值在其他列中出现的次数

c++ - 将 C++ 数组转换为 vector

c++ - 使用 glm 适当旋转 2D vector

java - 如果该方法返回枚举,则从 ArrayList 返回什么值?

vector - 使用 iter().filter().collect() 而不是 Vec<&string> 后如何获取 Vec<&String>

sql - 如何在 R 中表示非规范化表?

r - ggplot : How to create different x-axis titles with facet_grid

c++ - 我应该清理 ivar C++ vector ...吗?

r - 防止在使用save()或save.image()时覆盖文件