将嵌套for循环的结果存储到R中的矩阵中

时间:2017-01-27 05:13:04

标签: r for-loop matrix vector

我正在尝试创建一个矩阵,其中每一行代表通过for循环获得的向量中的数据。下面的代码在最终矩阵中只有一个数字,当它应该有5行60列时。每个gene_state向量的长度应为60,目标是将它们中的5个拼接在矩阵中,N = 5.

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
  }
}

1 个答案:

答案 0 :(得分: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