I am new to R. I want to fill in an empty matrix with the results of my for
loop using cbind
. My question is, how can I eliminate the NAs in the first column of my matrix. I include my code below:
output<-matrix(,15,) ##generate an empty matrix with 15 rows, the first column already filled with NAs, is there any way to leave the first column empty? for(`enter code here`){ normF<-`enter code here` output<-cbind(output,normF) }
The output is the matrix I expected. The only issue is that its first column is filled with NAs. How can I delete those NAs?
In R, one column is created by default for a matrix, therefore, to create a matrix without a column we can use ncol =0.
To create a matrix in R you need to use the function called matrix(). The arguments to this matrix() are the set of elements in the vector. You have to pass how many numbers of rows and how many numbers of columns you want to have in your matrix. Note: By default, matrices are in column-wise order.
A matrix having at least one dimension equal to zero is called an empty matrix. The simplest empty matrix is 0-by-0 in size. Examples of more complex matrices are those of dimension 0 -by- 5 or 10 -by- 0 -by- 20.
The default for matrix
is to have 1 column. To explicitly have 0 columns, you need to write
matrix(, nrow = 15, ncol = 0)
A better way would be to preallocate the entire matrix and then fill it in
mat <- matrix(, nrow = 15, ncol = n.columns) for(column in 1:n.columns){ mat[, column] <- vector }
If you don't know the number of columns ahead of time, add each column to a list and cbind
at the end.
List <- list() for(i in 1:n) { normF <- #something List[[i]] <- normF } Matrix = do.call(cbind, List)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With