简体   繁体   中英

Error in if (a[i][j] > 4) { : missing value where TRUE/FALSE needed

Find the number of entries in each row which are greater than 4.

set.seed(75)
aMat <- matrix( sample(10, size=60, replace=T), nr=6)

rowmax=function(a)
{
  x=nrow(a)
  y=ncol(a)
  i=1
  j=1
  z=0
  while (i<=x) {
    for(j in 1:y) {
      if(!is.na(a[i][j])){
       if(a[i][j]>4){
        z=z+1
        }
        }
      j=j+1
      }
    print(z)
    i=i+1
    }
  }

rowmax(aMat)

It is showing the error. I don't want to apply in built function

You could do this easier counting the x that are greater than 4 using length .

rowmax2 <- function(x) apply(x, 1, function(x) {x <- na.omit(x);length(x[x > 4])})
rowmax2(aMat)
# [1] 8 7 8 7 4 3

If you wanted to do this absolutely without any shortcut you could use two for loops. 1 for each row and another for each value in the row.

rowmax = function(a) {
  y=nrow(a)
  result <- numeric(y)
  for(j in seq_len(y)) {
    count = 0
    for(val in a[j, ]) {
      if(!is.na(val) && val > 4)
        count = count + 1
    }
      result[j] <- count
  }
  return(result)
}

rowmax(aMat)
#[1] 8 7 8 7 4 3

If you wanted to do this using in-built functions in base R you could use rowSums .

rowSums(aMat > 4, na.rm = TRUE)
#[1] 8 7 8 7 4 3

There are several errors in you code:

  1. You should put z <- 0 inside while loop
  2. You should use a[i,j] for the matrix indexing, rather than a[i][j]

Below is a version after fixing the problems

rowmax <- function(a) {
  x <- nrow(a)
  y <- ncol(a)
  i <- 1
  j <- 1
  while (i <= x) {
    z <- 0
    for (j in 1:y) {
      if (!is.na(a[i, j])) {
        if (a[i, j] > 4) {
          z <- z + 1
        }
      }
      j <- j + 1
    }
    print(z)
    i <- i + 1
  }
}

and then we get

> rowmax(aMat)
[1] 8
[1] 7
[1] 8
[1] 7
[1] 4
[1] 3

A concise approach to make it is using rowSums , eg,

rowSums(aMat, na.rm = TRUE)

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