2013-03-26 54 views
0

想象一下,橫跨x軸的顏色平滑,從左邊的白色到右邊的紅色。該梯度由x描述。生成過度混合的矢量

set.seed(444) 
x <-sort(runif(10,0,1)) 
x 
#[1] 0.04887351 0.05602405 0.16805309 0.18510214 0.28311653 0.36549003 0.38968610 
# 0.55943791 0.57680379 0.84906069 

在載體彼此旁邊x元素比更遠的序列中更相似。我可以隨機將這個矢量與sample(x,10)混合。但是如果我想洗牌x,以便彼此旁邊的數字(最近的鄰居)比彼此之間的數字更可能不同,那麼實現這一目標的好方法是什麼?

例如對於x的元素,其最接近的元素的平均之間的相關性是顯式:

neighbour <- c(x[2],mean(x[1],x[3]),mean(x[2],x[4]),mean(x[3],x[5]), 
       mean(x[4],x[6]),mean(x[5],x[7]),mean(x[6],x[8]), 
       mean(x[7],x[9]),mean(x[8],x[10]),x[9]) 
cor(x,neighbour) 
#[1] 0.9539783 

我想產生洗牌x以產生向量,其中cor()強烈負。

+0

也許你可以舉一個你想要輸出的例子嗎? – alexwhan 2013-03-26 08:38:58

回答

3

由於測試每個排列並採用最小值cor(因爲排列數爲10!即3 628 800)並不合理,您可以嘗試優化。這裏有一種方法:

a <- sort(runif(10,0,1)) 

#The function to minimize 
f<-function(par,vec){ 
    x<-vec[par] 
    neighbour <- c(x[2],mean(x[1],x[3]),mean(x[2],x[4]),mean(x[3],x[5]), 
       mean(x[4],x[6]),mean(x[5],x[7]),mean(x[6],x[8]), 
       mean(x[7],x[9]),mean(x[8],x[10]),x[9]) 
    cor(x,neighbour) 
    } 

# A function to generate a new permutation to test 
g<-function(par,vec){sample(par, length(par))} 

res <- optim(par=seq_along(a), fn=f, gr=g, vec=a, method="SANN", 
     control=list(maxit = 30000, temp = 2000, trace = TRUE, REPORT = 500)) 

你的結果是a[res$par]