简体   繁体   中英

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

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.

Try Ifelse condition in R

ifelse(nrow(df) >0, df[nrow(df),4]<- "ok",df[1,1]<- "No record found")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM