How to get the first nonzero element?

2

I have the following problem, I have an array and I want to go through it and get the first line that has all 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 from "a" would be line 2, the answer from "b" would be line 1 and the answer from "d" would be line 1.

Thank you in advance.

    
asked by anonymous 28.09.2015 / 16:21

1 answer

2

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 array and creates a vector, called vetor , which is TRUE when the line has all elements other than zero. Then it checks if there is at least a% w_ of% in that vector, then returns 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
    
28.09.2015 / 16:42