2017-01-27 50 views
0

我试图创建一个矩阵,其中每一行表示通过for循环获得的矢量中的数据。我的代码在最后一个矩阵中只有一个数字,当它应该有5行60列时。每个gene_state矢量应该是长度60的,并且其目的是在一个矩阵它们件5一起作为N = 5。将嵌套for循环的结果存储到R中的矩阵中

set.seed(1) 
N <- 5 
t <- 60 
myMatrix <- matrix(0, nrow=N, ncol=t) 
for(i in 1:N){ 
    gene_state <- 1 
    for(j in 1:t){ 
    randomNum <- runif(1) #runif(1) randomly generates a number between 0 and 1 
    if(gene_state == 1){  # if the gene_state is at 1 
     if(randomNum < 0.1){ # AND if the random number generated is less than 0.1 
     gene_state <- 2 # switch the state to 2 
     } else {  
     gene_state <- 1 # otherwise keep the state at 1 
     } 
    } else {   # if the gene_state is at 2 
     if(randomNum < 0.25){ # and if the random number is less than 0.25 
     gene_state <- 1 # switch the state to 1 
     }else{ 
     gene_state <- 2 # otherwise keep the state at 2 
     } 
    } 
    myMatrix[i,j] <- gene_state 
    } 
} 
+3

我得到一个5x60矩阵 – rawr

+0

@PaulR请让我知道你的推理是从这个问题中删除'换loop'标签是什么。 – Uwe

+0

@UweBlock:在这种情况下,它似乎不是一个特别有用的标签 - 我觉得添加缺少的'r'标签可能非常重要,'matrix'和'vector'标签是边界线的,所以我留下了它们in,但'for-loop'标签似乎没用。这只是我的看法 - 如果你认为它有一些价值,可以随意添加它, –

回答

1

我想的代码做的事情是为。我剪掉所有注释并重新排列最后一行

N <- 5 
t <- 60 
myMatrix <- matrix(0, nrow=N, ncol=t) 
for(i in 1:N){ 
    gene_state <- 1 
    for(j in 1:t){ 
     randomNum <- runif(1) 
     if(gene_state == 1){ 
      if(randomNum < 0.1){ 
       gene_state <- 2 
      } else {  
       gene_state <- 1 
      } 
     } else { 
      if(randomNum < 0.25){ 
       gene_state <- 1 
      }else{ 
       gene_state <- 2 
      } 
     } 
     myMatrix[i,j] <- gene_state 
    }} 

这导致了5 x 60矩阵。

dim(myMatrix) 
[1] 5 60 
+0

谢谢!它现在有效,不知道为什么它有一天给了我不同的东西...... – Sarah