adaodante - 8 months ago 39

R Question

So essentially I have two matrices:

`A<-matrix(runif(10*10),ncol = 10)`

B<-matrix(runif(10*10),ncol = 10)

I am trying to create a for loop which will:

a)remove the top row of matrix A and and add the top row of matrix B to the bottom of the new matrix A, to create a matrix a.

b)remove the 2 top rows of matrix A and and add the 2 top rows of matrix B to the bottom of the new matrix A,to create a matrix b

c)remove the 3 top rows of matrix A and and add the 3 top rows of matrix B to the bottom of the new matrix A, to create a matrix c

. . .

I could write this manually like the code below shows, but I need to do this for a bigger matrix so it will take me much longer:

`a<-rbind(A[2:10,],B[1:1,])`

b<-rbind(A[3:10,],B[1:2,])

c<-rbind(A[4:10,],B[1:3,])

d<-rbind(A[5:10,],B[1:4,])

.

.

.

Here is my attempt at creating the for loop:

`A<-matrix(c(rep(0,10*10)),nrow=10)`

n<-10

for (i in 1:n-1){

A<-rbind(R[(i+1):10,],ER[(1:i),])

}

This only outputs the n-1 matrix, but I would like all my matrices to be output.

Answer

This function does what you want for an arbitrary number of rows `nrows`

```
switch_matrices <- function(mat1, mat2, nrows){
rbind(mat1[(1+nrows):nrow(mat1),],mat2[1:nrows,])
}
```

You can check that it works

```
all.equal(rbind(A[2:10,],B[1:1,]) ,switch_matrices(A,B, 1))
```

Make a list with all of your data frames in each list element.

```
l <- lapply(1:9, function(nrows) switch_matrices(A,B, nrows))
```

If you want to make each element of list `l`

a separate variable in your global environment you can use

```
list2env(setNames(l,paste0("AB",seq_along(l))), envir = parent.frame())
```