Matrices in R programming

I am new to R programming and have few questions regarding matrices in R.

I have a function that returns a matrix. I want to check if the returned matrix is ​​empty or not. How can I test it in R? If it's an integer, we can check for is.null(someinteger)

. But how can we check them in the case of matrices?

Alternatively, an integer can be initialized with x <- NULL

. If I just want to initialize the matrix. We initialize as mat <- matrix()

or is there any other way? mat

can be of any size.

Thankyou.

+3


source to share


2 answers


There is a question as to what is meant by "empty" here, but this will check if the matrix m

is of length zero:

length(m) == 0

      

As for matrix initialization, this initializes it as a 0x0 matrix:

m <- matrix(, 0, 0)

      

and this makes it be a 1x1 matrix containing NA:



m <- matrix()

      

and this initializes it with a matrix nr

on nc

NA values:

m <- matrix(, nr, nc)

      

It's unclear if this is actually useful. You can describe what you are trying to accomplish. Why do you need to initialize it at all?

+2


source


Try:

all(is.na(m))

      

Or:



is.logical(m)

      

Can act as a single function test. If one is numeric

or character

is a list element, it will return FALSE

. The second solution should work; it seems that your function is creating matrices with numbers and / or NA.

+1


source







All Articles