I have assignment using R and have a little problem. In the assignment several matrices have to be generated with random number of rows and later used for various calculations. Everything works perfect, unless number of rows is 1.
In the calculations I use nrow(matrix) in different ways, for example if (i <= nrow(matrix) ) {action}
and also statements like matrix[,4]
and so on.
So in case number of rows is 1 (I know it is actually vector) R give errors, definitely because nrow(1-dimensional matrix)=NULL. Is there simple way to deal with this? Otherwise probably whole code have to be rewritten, but I'm very short in time :(
nrow() function in R Language is used to return the number of rows of the specified matrix. Syntax: nrow(x)
The nrow R function returns the number of rows that are present in a data frame or matrix.
Matrices are the two-dimensional data structures in R that allow us to store the data into the form of rows and columns and have a dedicated function named matrix() that allows us to create them in the R environment.
Description. nrow and ncol return the number of rows or columns present in x . NCOL and NROW do the same treating a vector as 1-column matrix, even a 0-length vector, compatibly with as. matrix() or cbind() , see the example.
It is not that single-row/col matrices in R have ncol
/nrow
set to NULL
-- in R everything is a 1D vector which can behave like matrix (i.e. show as a matrix, accept matrix indexing, etc.) when it has a dim
attribute set. It seems otherwise because simple indexing a matrix to a single row or column drops dim
and leaves the data in its default (1D vector) state.
Thus you can accomplish your goal either by directly recreating dim
attribute of a vector (say it is called x):
dim(x)<-c(length(x),1)
x #Now a single column matrix
dim(x)<-c(1,length(x))
x #Now a single row matrix
OR by preventing []
operator from dropping dim
by adding drop=FALSE
argument:
x<-matrix(1:12,3,4)
x #OK, matrix
x[,3] #Boo, vector
x[,3,drop=FALSE] #Matrixicity saved!
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