简体   繁体   中英

R how to use loop functions to create a matrix

I want to create a large matrix consists of a series of smaller ones. There are 30 small 30 x 3153 matrixs. Each has only one row of 1s, and the rest are all 0s. The position of the row of 1s goes from 1 to 30. For example, in the 1st matrix, the 1s are on row 1, 2nd matrix on row 2, etc.

Since I'm new to programming, I'm not sure how to use a loop function to achieve this. I don't know how to pass a variable to the loop function.

Here's what I've tried.

  1. Created two vectors of 0s and 1s.
  2. built a 29 x 3153 matrix with only 0s.
  3. Use the insertRow function in the miscTools package to insert the 1s into according position
  4. Then cbind all matrix to create the large one I want.

I'm stuck with how to use a loop to accomplish this. I'm much appreciated if anybody can help me. Thanks

vec0=rep.int(0,n)
vec1=rep.int(1,n)
uij=matrix(rep(vec0,c-1),nrow=c-1,ncol=n)

Uij=cbind(lapply(uij,insertRow(uij,i,vec1)))
hold_mat <- list()
for(i in seq(30)){
  mat <- matrix(0, nrow = 30, ncol = 3153)
  mat[i, ] <- 1
  hold_mat[[i]] <- mat
}

bigMatrix <- do.call(rbind, hold_mat)

EDIT: Here is a solution with sparse matrices from the Matrix package:

library(Matrix)
numRows <- 30
numCols <- 3152
hold_mat <- lapply(seq(numRows), function(k) sparseMatrix(i = rep(k, numCols), j = seq(numCols), dims = c(numRows, numCols))) 
bigMatrix <- do.call(rBind, hold_mat)

> str(bigMatrix)
Formal class 'ngCMatrix' [package "Matrix"] with 5 slots
..@ i       : int [1:94560] 0 31 62 93 124 155 186 217 248 279 ...
..@ p       : int [1:3153] 0 30 60 90 120 150 180 210 240 270 ...
..@ Dim     : int [1:2] 900 3152
..@ Dimnames:List of 2
.. ..$ : NULL
.. ..$ : NULL
..@ factors : list()

Think of what each row of the big matrix will look like:

1 - 29 times 0 - 0 - 1 - 28 times 0 - 0 - 0 - 1 - 27 times 0 - ...

So essentially you have:

[1 - 30 times 0] x 30 times - 1

This is repeated over 3153 rows.

So you can just use:

row <- c(rep( c(1, rep(0, 30)), 30), 1)
m <- matrix(rep(row, 3153), nrow=3153)

Where:

c(1, rep(0, 30)) # one followed by 30 zeros

rep( c(1, rep(0, 30)), 30) # 1 and 30x 0 repeated 30 times

c(rep( c(1, rep(0, 30)), 30), 1) # 1 and 30x 0 rep 30 times and 1 at the end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM