如何连接列表中的矩阵
问题描述:
我有一个问题。如何连接列表中的矩阵
我有代码:
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”矩阵连接做些什么?
谢谢。
答
试试这个:
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'可以实现这一点。
是的!谢谢! – Dmitriy
是的,我已经这样做了。 ))Stackoverflow允许在同一时间后(10分钟,我想:-() – Dmitriy