Hi,
Try this:
mat1: 1st matrix
mat2: 2nd matrix
fun1<- function(x){
big<- x>0.8*max(x)
n<- length(big)
startRunOfBigs<- which(c(big[1],!big[-n] & big[-1]))
endRunOfBigs<- which(c(big[-n] & !big[-1], big[n]))
index<- vapply(seq_along(startRunOfBigs),function(i) which.max(x[startRunOfBigs[i]:endRunOfBigs[i]])+startRunOfBigs[i]-1L,0L)
index<-ifelse(sum(
is.na(match(index,c(1,12))))==0 & x[index]!=max(x[index]), NA,index)
data.frame(Index=index[!
is.na(index)],Value=x[index[!
is.na(index)]])
}
fun2<- function(mat){
vec1<- sapply(seq_len(ncol(mat)),function(i){
x<-mat[,i]
x1<-fun1(mat[,i])
x2<- x1$Index[which.min(abs(x1$Index-length(x)))]
})
indx<- if(abs(diff(vec1)) > (nrow(mat)/2)){
nrow(mat)-abs(diff(vec1))
}
else(abs(diff(vec1)))
res1<-sapply(seq(indx),function(i){
x3<- mat[,2]
indx1<-seq(length(x3)-i)
indx2<-c(setdiff(seq_along(x3),indx1),indx1)
sum(abs(mat[,1]-x3[indx2]))
})
res2<- sum(res1)
res2
}
fun2(mat1)
#[1] 40.93609
fun2(mat2)
#[1] 12.79153
#Using the method that I send yesterday: (just to confirm the calculation for mat1. It won't work with mat2)
sum(sapply(which.max(rev(mat1[,2])):which.max(mat1[,1]),function(i) {x<-seq(nrow(mat1))-i; x[x<=0]<-seq(max(x)+1,nrow(mat1),1);sum(abs(mat1[,1]-mat1[x,2]))}))
#[1] 40.93609
A.K.
______________________________________________
R-h...@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide
http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.
______________________________________________
R-h...@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide
http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.