【问题标题】:append elements with unique rownames to matrix in a R loop将具有唯一行名的元素附加到 R 循环中的矩阵
【发布时间】:2021-11-24 10:33:58
【问题描述】:

您能帮我在我的结局矩阵中获得自定义的暗名吗?

mat=matrix(nrow = 1, ncol = 5) #create empty matrix to hold values

#run for loop to generate random numbers and append to matrix
for(i in 1:2) {
  rad5 = matrix(runif(n=5, min = 0, max = 3+i),nrow = 1, ncol = 5, dimnames = list(c("row_Name1"), c(paste0("col",letters[1:5]))))
  #mat[i,] <- rad5

  mat = rbind(mat[i], rad5)
  }

这是我想要的示例。谢谢

> mat
              cola     colb     colc      cold     cole
row_Name1 2.559102 2.559102 2.559102 2.5591017 2.559102
row_Name2 1.466036 4.942660 1.833257 0.7989867 3.981458

【问题讨论】:

    标签: r loops matrix


    【解决方案1】:

    不需要索引。将 matrix 初始化为 0 行,然后将 rbindmat 初始化为“rad5”

    mat <- matrix(nrow = 0, ncol = 5)
    for(i in 1:2) {
      rad5 <- matrix(runif(n=5, min = 0, max = 3+i),nrow = 1, ncol = 5, 
             dimnames = list(paste0("row_Name", i),  
                            c(paste0("col",letters[1:5]))))
    
      mat <- rbind(mat, rad5)
      }
    

    -输出

    > mat
                  cola     colb     colc     cold     cole
    row_Name1 1.282858 2.881827 1.569325 1.122946 3.092109
    row_Name2 2.928784 2.040826 2.023392 4.823843 1.546266
    

    【讨论】:

      【解决方案2】:

      您也可以在循环之外添加名称

      mat=matrix(nrow = 1, ncol = 5) #create empty matrix to hold values
      
      #run for loop to generate random numbers and append to matrix
      for(i in 1:2) {
        rad5 = matrix(runif(n=5, min = 0, max = 3+i),nrow = 1, ncol = 5)
        mat = rbind(mat[i], rad5)
      }
      
      dimnames(mat) <- list(paste0("row_Name",1:nrow(mat)),c(paste0("col",letters[1:ncol(mat)])))
      
      mat 
      
                    cola     colb      colc     cold     cole
      row_Name1 0.373359 0.373359 0.3733590 0.373359 0.373359
      row_Name2 2.449678 4.738450 0.5484266 3.138387 2.011238
       
      

      【讨论】:

        猜你喜欢
        • 2021-12-31
        • 2021-05-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-08-12
        相关资源
        最近更新 更多