2016-07-05 135 views
0

我有一個問題。如何連接列表中的矩陣

我有代碼:

RootBootstrapping <- function(mean, sd) 
{ 
    polyCoeffs <- rnorm(length(mean), mean = mean, sd = sd); 

    rawResult <- as.complex(polyroot(polyCoeffs)); 
    roots <- rawResult[order(Re(rawResult), Im(rawResult))]; 

    rootMatrix <- matrix(nrow = (length(polyCoeffs) - 1), ncol = 2); 
    colnames(rootMatrix) <- c("Re", "Im"); 

    rootMatrix[,"Re"] <- Re(roots); 
    rootMatrix[,"Im"] <- Im(roots); 

    return (rootMatrix); 
} 

points <- 5 
polyMatrixCoeff <- matrix(c(1, 0, 0.5, 0.01, 0.3, 0.02), nrow = 3, ncol = 2); 
colnames(polyMatrixCoeff) <- c("mean", "sd"); 

meanRoots <- as.complex(polyroot(polyMatrixCoeff[,"mean"])); 

rootsCount <- length(polyMatrixCoeff[,"mean"]) - 1; 

我想從RootBootstrapping的多次運行串聯「byrow」的結果 - 我想有NX2矩陣「重」和「IM」欄目。

但下面的代碼無法正常工作......

rootsMatrix <- rbind(sapply(1:points, function(i) 
        { 
         roots <- RootBootstrapping(mean = polyMatrixCoeff[,"mean"], sd = polyMatrixCoeff[,"sd"]); 
         print(roots); 
         return (roots); 
        }) 
        ); 
rootsMatrix 

運行這段代碼,我有:

   Re  Im 
[1,] -0.8396051 -1.614007 
[2,] -0.8396051 1.614007 
      Re  Im 
[1,] -0.8826579 -1.650071 
[2,] -0.8826579 1.650071 
      Re  Im 
[1,] -0.8182654 -1.600865 
[2,] -0.8182654 1.600865 
      Re  Im 
[1,] -0.7379369 1.566913 
[2,] -0.7379369 -1.566913 
      Re  Im 
[1,] -0.7958687 -1.575169 
[2,] -0.7958687 1.575169 
> 
> rootsMatrix 
      [,1]  [,2]  [,3]  [,4]  [,5] 
[1,] -0.8396051 -0.8826579 -0.8182654 -0.7379369 -0.7958687 
[2,] -0.8396051 -0.8826579 -0.8182654 -0.7379369 -0.7958687 
[3,] -1.6140074 -1.6500706 -1.6008651 1.5669132 -1.5751692 
[4,] 1.6140074 1.6500706 1.6008651 -1.5669132 1.5751692 
> 

,但我想這一點:

   Re  Im 
[1,] -0.8396051 -1.614007 
[2,] -0.8396051 1.614007 
[3,] -0.8826579 -1.650071 
[4,] -0.8826579 1.650071 
[5,] -0.8182654 -1.600865 
[6,] -0.8182654 1.600865 
[7,] -0.7379369 1.566913 
[8,] -0.7379369 -1.566913 
[9,] -0.7958687 -1.575169 
[10,] -0.7958687 1.575169 

那麼,是什麼我應該爲「byrow」矩陣連接做些什麼?

謝謝。

回答

1

試試這個:

boots_m <- do.call('rbind', lapply(1:points, function(i) 
{ 
    RootBootstrapping(mean = polyMatrixCoeff[,"mean"], sd = polyMatrixCoeff[,"sd"]); 
})) 

       Re  Im 
[1,] 0.066901733 -1.399761 
[2,] 0.066901733 1.399761 
[3,] 0.047678284 -1.424875 
[4,] 0.047678284 1.424875 
[5,] 0.770198137 -1.183426 
[6,] 0.770198137 1.183426 
[7,] 0.314456296 -1.408569 
[8,] 0.314456296 1.408569 
[9,] -0.004113855 -1.445197 
[10,] -0.004113855 1.445197 

sapply試圖簡化的結果,所以有時會使用更安全lapply如果您的最終目標是連接值在一起。使用do.call函數中的'rbind'可以實現這一點。

+0

是的!謝謝! – Dmitriy

+0

是的,我已經這樣做了。 ))Stackoverflow允許在同一時間後(10分鐘,我想:-() – Dmitriy