How to get the first non-zero element?

Asked

Viewed 857 times

3

I have the following problem, I have a matrix and I want to go through it and get the first line that has all the elements other than zero. For example:

a = matrix(c(rep(0,4), 1:16), ncol = 4, byrow = T)
b = matrix(c(1:4, rep(0,4), 5:16), ncol = 4, byrow = T)
d = matrix(c(1:8,rep(0,4) , 9:16), ncol = 4, byrow = T)

The answer to "a" would be line 2, the answer to "b" would be line 1 and the answer to "d" would be line 1.

Thanks in advance.

1 answer

3


Try the following function:

primeira_linha_nao_nula <- function(m){
  vetor <- apply(m, 1, function(x) return(all(x != 0)))
  indice <- NULL
  if(max(vetor) == 1){
    indice <- order(vetor, decreasing = T)[1]  
  }
  return(m[indice,])
}

The first line runs through the matrix and creates a vector, called vetor, that is TRUE when the line has all non-zero elements. Then she checks if there is at least one TRUE in that vector, to then return the lowest index that is TRUE.

> primeira_linha_nao_nula(a)
[1] 1 2 3 4
> primeira_linha_nao_nula(b)
[1] 1 2 3 4
> primeira_linha_nao_nula(d)
[1] 1 2 3 4
  • 1

    Daniel, I expressed myself wrong, I want you to return the elements of the matrix, that is, all the elements of line 2, 1 and 1.

  • I’ll edit, but it’s just one more line!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.