Reputation: 147
I am new to R programming, and I 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 do I check it in R? If it is an integer, we can check it by is.null(someinteger)
. But how do we check the same in the case of matrices?
Also, an integer can be initialized by x <- NULL
. If I have just wanted to initialize a matrix. Do we initialize like mat <- matrix()
or is there any other way? mat
can be of any size.
Upvotes: 3
Views: 355
Reputation: 1
If your only concern is that your function returns a matrix then regardless of what your preceding data types/structures are you could always just finalize the output as a matrix unless you need the preceding data processing to work with a matrix structure, which doesn't sound the like problem at all.
see fundamental example below:
x <- c(1:5)
y <- c(6:10)
foo <- function(x, y){
z <- cbind(x,y)
return(as.matrix(z))
}
z <-foo(x,y)
z
Upvotes: 0
Reputation: 269654
There is some question of what is meant by "empty" here but this will test if matrix m
has zero length:
length(m) == 0
Regarding initializing a matrix this initializes it to be a 0x0 matrix:
m <- matrix(, 0, 0)
and this initalizes it to be a 1x1 matrix containing NA:
m <- matrix()
and this initializes it to an nr
by nc
matrix of NA values:
m <- matrix(, nr, nc)
Not clear whether any of these are actually useful. You may want to describe what you are trying to accomplish. Why do you need to initialize it at all?
Upvotes: 2
Reputation: 28441
Try:
all(is.na(m))
Or:
is.logical(m)
Can act as a single function test. If one numeric
or character
is an element of the list, it will return FALSE
. The second solution should work; it appears that your function is creating matrices with numbers and/or NAs.
Upvotes: 1