2014-11-06 46 views
0

在循環改變參數循環數循環假設針對我有以下行向量newdata.forgm[1,]說明目的:只在一個與R中

 X2  X3  X4  X5  X6  X7  X8  X9  X10  x11 
3.804125 4.480942 5.023256 5.453471 5.790166 6.048769 6.24211 6.380872 6.473965 6.528837 

X12 ....  X36 
6.55172....4.26642 

其中X1除去。

我想創建一個帶有30種產品的每一行下面的行向量以下矩陣:

(X2*X3)^(1/2) (X2*X3*X4)^(1/3)  (X2*X3*X4*X5)^(1/4) ... (X2*...*X32)^(1/31) 
(X3*X4)^(1/2) (X3*X4*X5)^(1/3)  (X3*X4*X5*X6)^(1/4) ... (X3*...*X33)^(1/31) 
(X4*X5)^(1/2) (X4*X5*X6)^(1/3)  (X4*X5*X6*X7)^(1/4) ... (X4*...*X34)^(1/31) 
(X5*X6)^(1/2) (X5*X6*X7)^(1/3)  (X5*X6*X7*X8)^(1/4) ... (X5*...*X35)^(1/31) 
(X6*X7)^(1/2) (X6*X7*X8)^(1/3)  (X6*X7*X8*X9)^(1/4) ... (X6*...*X36)^(1/31) 

我有下列R-代碼:

n=31 
prod.spe <- function(x) { 
    answ <- NULL 
    for(i in 2:n) { 
     answ <- c(answ, (prod(x[1:(i+0)]))^(1/i)) 
    } 
    return(answ) 
} 
prod.spe(newdata.forgm[1,]) 


prod.spe <- function(x) { 
    answ <- NULL 
    for(i in 2:n) { 
     answ <- c(answ, (prod(x[2:(i+1)]))^(1/i)) 
    } 
    return(answ) 
} 
prod.spe(newdata.forgm[1,]) 

prod.spe <- function(x) { 
    answ <- NULL 
    for(i in 2:n) { 
     answ <- c(answ, (prod(x[3:(i+2)]))^(1/i)) 
    } 
    return(answ) 
} 
prod.spe(newdata.forgm[1,]) 

prod.spe <- function(x) { 
    answ <- NULL 
    for(i in 2:n) { 
     answ <- c(answ, (prod(x[4:(i+3)]))^(1/i)) 
    } 
    return(answ) 
} 
prod.spe(newdata.forgm[1,]) 

    prod.spe <- function(x) { 
    answ <- NULL 
    for(i in 2:n) { 
     answ <- c(answ, (prod(x[5:(i+4)]))^(1/i)) 
    } 
    return(answ) 
} 
prod.spe(newdata.forgm[1,]) 

我怎麼能只寫一個R中的迴路佔0,1,2,3,4和1,2,3,4,5的變化(見上文這些數字如何變化)。您的反饋將不勝感激。

+1

你循環是非常低效的。學習預先分配。然後學習矢量化(即,你可以使用'cumprod'函數)。 – Roland 2014-11-06 18:55:39

+0

對不起羅蘭,'newdata.forgm [1,]'是一個數字的行向量,你可以看到矩陣符號。 newdata.forgm [1,]是一個data.frame – coco 2014-11-06 18:59:04

+0

對不起,編輯時我犯了重複它的錯誤,但現在它已被修復。感謝Richard! – coco 2014-11-06 19:43:48

回答

0

這裏是回答我的問題:

n=31 
prod.spe1 <- function(x) { 
asnansw <- NULL 
for(i in 2:n) { 
    for (j in 0:4) { 
    answ <- c(answ, (prod(x[(j+1):(i+j)]))^(1/i)) 
     } 
    } 
return(answ) 
} 
matrix((prod.spe1(newdata.forgm[1,])),nrow=5,ncol=30)