如何从列表中连接矩阵

时间:2016-07-05 12:35:42

标签: r matrix sapply

我有一个问题。

我有代码:

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矩阵带有“Re”和“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 个答案:

答案 0 :(得分: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'将实现此目的。