我已经编写了一个小递归函数,它将在您传递的向量中找到所有连续的三元组(至少需要传递三个)。它可能有点粗糙,但似乎有效。
该函数使用省略号... 来传递参数。因此,无论您提供多少参数(即数字向量),它都会将它们放入列表items 中。然后找到每个传递的向量中的最小值及其索引。
然后使用for() 循环创建和迭代与最小三元组对应的向量的索引,其中输出值被传递到输出向量out。 items 中的输入向量被修剪并以递归方式再次传递给函数。
只有当所有向量都是NA,即向量中没有更多值时,函数才会返回最终结果。
library(magrittr)
# define function to find the triplets
tripl <- function(...){
items <- list(...)
# find the smallest number in each passed vector, along with its index
# output is a matrix of n-by-2, where n is the number of passed arguments
triplet.id <- lapply(items, function(x){
if(is.na(x) %>% prod) id <- c(NA, NA)
else id <- c(which(x == min(x)), x[which(x == min(x))])
}) %>% unlist %>% matrix(., ncol=2, byrow=T)
# find the smallest triplet from the passed vectors
index <- order(triplet.id[,2])[1:3]
# create empty vector for output
out <- vector()
# go through the smallest triplet's indices
for(i in index){
# .. append the coresponding item from the input vector to the out vector
# .. and remove the value from the input vector
if(length(items[[i]]) == 1) {
out <- append(out, items[[i]])
# .. if the input vector has no value left fill with NA
items[[i]] <- NA
}
else {
out <- append(out, items[[i]][triplet.id[i,1]])
items[[i]] <- items[[i]][-triplet.id[i,1]]
}
}
# recurse until all vectors are empty (NA)
if(!prod(unlist(is.na(items)))) out <- append(list(out),
do.call("tripl", c(items), quote = F))
else(out <- list(out))
# return result
return(out)
}
可以通过将输入向量作为参数传递来调用该函数。
# input vectors
a = c(3,5)
b = c(6,1,8,7)
c = c(4,2,9)
# find all the triplets using our function
y <- tripl(a,b,c)
结果是一个列表,其中包含所有必要的信息,尽管是无序的。
print(y)
# [[1]]
# [1] 1 2 3
#
# [[2]]
# [1] 4 5 6
#
# [[3]]
# [1] 7 9 NA
#
# [[4]]
# [1] 8 NA NA
可以使用sapply():
# put everything in order
sapply(y, function(x){x[order(x)]}) %>% t
# [,1] [,2] [,3]
# [1,] 1 2 3
# [2,] 4 5 6
# [3,] 7 9 NA
# [4,] 8 NA NA
问题是,每个向量只使用一个值来查找三元组。
因此它将找不到连续的三元组c(6,7,8),例如c(6,7,11)、c(8,9,13) 和 c(10,12,14)。
在这种情况下,它将返回 c(6,8,10)(见下文)。
a<-c(6,7,11)
b<-c(8,9,13)
c<-c(10,12,14)
y <- tripl(a,b,c)
sapply(y, function(x){x[order(x)]}) %>% t
# [,1] [,2] [,3]
# [1,] 6 8 10
# [2,] 7 9 12
# [3,] 11 13 14