Lcat91
Lcat91

Reputation: 794

If else statement in R

So I am trying to create an if statement where if the number of columns is greater than 1 then it will do several forms of manipulation to that matrix, and if the matrix has less then or equal 1 columns it will not do the analysis. Here's some of the code:

M <- NxN matrix

 if (ncol(M) > 1) {
      function1
      function2
      function3
      ...
 }
 else {}

However, when I do this I keep getting the following error:

 Error in if (ncol(M) > 1) { : argument is of length zero

Upvotes: 1

Views: 9636

Answers (1)

user1566811
user1566811

Reputation:

Your M object is probably not a matrix. We'll create a matrix and see what your code outputs, then we'll explore a way you might have accidentally changed it to a vector, and then we'll see how to subset a matrix without ending up with a vector by mistake.

N <- 10
M <- matrix(sample(1:100, N*N, replace=TRUE), N, N)

colTest <- function(M) {
    if (ncol(M) > 1) {
        print("More than one column.")
    } else {
        print("One or fewer columns.")
    }
}
colTest(M)
M.vector <- M[, 2]
colTest(M.vector)
class(M.vector)
M.submatrix <- M[, 2, drop=FALSE]
colTest(M.submatrix)
class(M.submatrix)

Output:

[1] "More than one column."
Error in if (ncol(M) > 1) { : argument is of length zero
[1] "integer"
[1] "One or fewer columns."
[1] "matrix"

In the future, when you have problems like this one, give the str and class functions a try: they will show you the structure and class of any object.

Upvotes: 4

Related Questions