[R] generating a matrix after a for loop..
Greg Snow
Greg.Snow at imail.org
Sat Nov 28 20:01:59 CET 2009
Let me see if I understand your question.
You want to run your simulation function (mclustSim) several times and collect the resulting vector from each run into a matrix. Is that correct?
In that case you can just you the replicate command (as long as your function returns the same length vector each time). It runs a command or function multiple times and simplifies the results (into a matrix if the return is a vector).
Something like:
> outmat <- replicate( 10, mclustSim(rnorm(25)) )
> outmat
Hope this helps,
--
Gregory (Greg) L. Snow Ph.D.
Statistical Data Center
Intermountain Healthcare
greg.snow at imail.org
801.408.8111
> -----Original Message-----
> From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-
> project.org] On Behalf Of John Seppänen
> Sent: Friday, November 27, 2009 4:30 AM
> To: r-help at r-project.org
> Subject: [R] generating a matrix after a for loop..
>
> Hi all,
>
> I have to ask this and I know that the reason is that I am a newbie
> with R
> programming. So apologize if it is too obvious but I didn't find an
> answer
> after googling and reading "An introduction to R". So i have return
> data from 30 instruments and I am fitting a mixture of normal
> distributions for the asymmetric marginal distributions and then
> simulating
> from those distributions. For this I have tried to build a function as
> below
>
>
>
>
> "mclustSim" <- function(x){
>
> library(mclust)
> nr=dim(x)[1]
> nc=dim(x)[2]
> NumberOfSim=100
>
> for (i in 1:nc){
> y<-Mclust(as.matrix(x[,i]))
> z<-sim(modelName=y$modelName,parameters=y$parameters,n=NumberOfSim)
> #print(c(colnames(x[i]),z[,2]),digits=3)
>
> }
> }
>
> z is the simulated return series. How can I say: "print z next to
> previous
> z and form a matrix"
> How could I get an matrix as a result..? So that I would have
> simulations
> from asset1 distribution at first column, simulation from asset2 at
> second
> column etc. And the result would be NumberOfSim X Ncol matrix..
>
> Thanks for any help
>
> Br,
> John
>
> [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-
> guide.html
> and provide commented, minimal, self-contained, reproducible code.
More information about the R-help
mailing list