Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create an empty matrix in R?

Tags:

r

na

matrix

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?

like image 632
user3276582 Avatar asked Feb 05 '14 18:02

user3276582


People also ask

How do you create an empty matrix in R studio?

In R, one column is created by default for a matrix, therefore, to create a matrix without a column we can use ncol =0.

How can I create a matrix in R?

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.

Can a matrix be empty?

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.


2 Answers

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 } 
like image 50
Christopher Louden Avatar answered Sep 21 '22 04:09

Christopher Louden


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) 
like image 21
Señor O Avatar answered Sep 22 '22 04:09

Señor O