我正在尝试对几个数据库运行代码,这些数据库的主要部分取决于下一个代码。下面定义的函数用于从Bandt和Pompe计算置换熵,基本上从时间序列中的所有可能的嵌入窗口捕获所有可能的置换。
让我们假设我的时间序列由ts = (1, 2, 3.5, 1.2, 4.6, 5.2, 2.1, 1.9)
给出,我的嵌入维数(D
)为4
;从ts中获取前4个元素,我得到(1,2,3.5,1.2)
,其排列方式由(0,2,3,1)
给出,因为向量中的第一个元素是向量中的最小值,第四个是向量中的第二个小元素等等。我需要从ts获取所有这些排列,以便计算排列熵。
prob_perm_desl <- function(serie, D) {
require(permute)
#TS length
n <- length(serie)
#Matrix where D-dimensional vectors will be saved
#Z <- matrix(nrow=num_fil, ncol=D)
A <- list()
for(i in 1:D) {
k <- (n-i+1)%/%D #Number of windows of dimension D along the ts
len <- k*D+i-1 #Position of the last element in the serie that will be in the matrix
A[[i]] <- matrix(serie[i:len], ncol=D, byrow = TRUE)
}
A_bis <- do.call("rbind",A) #Matriz of all D-dimensional vectors in ts
A_pasted <- t(apply(A_bis,1, order)) #order used to get permutations patterns
Z_concat <- apply(A_pasted, 1,paste0, collapse="_") #All possible permutation patterns in ts concatenated in order to compare
permutaciones <- rbind(seq(1:D), allPerms(D)) #all posible permutation patterns
permutaciones_concat <- apply(permutaciones, 1, paste0, collapse="_") #concatenated patterns in order to compare
#counts how many times all posible permutation patterns appear in ts
conteos <- sapply(list(Z_concat), function(x) {
sapply(permutaciones_concat,function(y) sum(x %in% y) )
})
prob <- conteos/sum(conteos)
return(prob)
}
我的问题是这部分代码要花很多时间
A_pasted<-t(apply(A_bis,1, order)) #order used to get permutations patterns
Z_concat<-apply(A_pasted, 1,paste0, collapse="_") #All possible permutation patterns in ts concatenated in order to compare
并且我需要优化时间,因为我不得不大量应用该函数。