Home > Software design >  append elements with unique rownames to matrix in a R loop
append elements with unique rownames to matrix in a R loop

Time:10-04

could you please help me get my customized dimnames in my finale matrix?

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

this is example of what I want. Thanks

> 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

CodePudding user response:

The indexing is not required. Initialize the matrix as 0 rows and just rbind the mat with the 'rad5' created

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

-output

> 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

CodePudding user response:

You could also add the names outside the loop

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
 
  • Related