Fill matrix with loop

我怕爱的太早我们不能终老 提交于 2021-02-07 14:30:33

问题


I am trying to create a matrix n by k with k mvn covariates using a loop. Quite simple but not working so far... Here is my code:

n=1000
k=5
p=100
mu=0
sigma=1
x=matrix(data=NA, nrow=n, ncol=k)


for (i in 1:k){
        x [[i]]= mvrnorm(n,mu,sigma)
       }

What's missing?


回答1:


I see several things here:

  1. You may want to set the random seed for replicability (set.seed(20430)). This means that every time you run the code, you will get exactly the same set of pseudorandom variates.
  2. Next, your data will just be independent variates; they won't actually have any multivariate structure (although that may be what you want). In general, if you want to generate multivariate data, you should use ?mvrnorm, from the MASS package. (For more info, see here.)
  3. As a minor point, if you want standard normal data, you don't need to specify mu = 0 and sigma = 1, as those are the default values for rnorm().
  4. You don't need a loop to fill a matrix in R, just generate as many values as you like and add them directly using the data= argument in the matrix() function. If you really were committed to using a loop, you should probably use a double loop, so that you are looping over the columns, and within each loop, looping over the rows. (Note that this is a very inefficient way to code in R--although I do things like that all the time ;-).
  5. Lastly, I can't tell what p is supposed to be doing in your code.

Here is a basic way to do what you seem to be going for:

set.seed(20430)
n   = 1000
k   = 5
dat = rnorm(n*k)
x   = matrix(data=dat, nrow=n, ncol=k)

If you really wanted to use loops you could do it like this:

mu    = 0
sigma = 1
x     = matrix(data=NA, nrow=n, ncol=k)

for(j in 1:k){
   for(i in 1:n){
        x[i,j] = rnorm(1, mu, sigma)
   }
}



回答2:


A=c(2,3,4,5);# In your case row terms
B=c(3,4,5,6);# In your case column terms
x=matrix(,nrow = length(A), ncol = length(B));
for (i in 1:length(A)){
     for (j in 1:length(B)){
          x[i,j]<-(A[i]*B[j])# do the similarity function, simi(A[i],B[j])       
     }
}
x # matrix is filled

I was thinking in my problem perspective.




回答3:


define the matrix first

E<-matrix(data=0, nrow=10, ncol=10);

run two loops to iterate i for rows and j for columns, mine is a exchangeable correlation structure

for (i in 1:10)
{ 
  for (j in 1:10) 
  {
    if (i==j) {E[i,j]=1}
    else {E[i,j]=0.6}
  }
};


来源:https://stackoverflow.com/questions/14685911/fill-matrix-with-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!