Find first occurrence in list

I have a 3D matrix and I would like to find the index of the first occurrence of a number below 0 in one of its columns. I know to get the column you would have to do something like matrix3D[, 1, 1] but I don't know how to get the index of the first negative element. Would anyone be able to tell me if there is a function for this?

I wrote a little function that gives the row, column and shelf of the first negative number. I think it works generally. The operator %% returns the mod and %/% is integer division.


set.seed(2)
Arr <- array(runif(27, -1, 10), dim = c(3,3,3))
Arr
#> , , 1
#> 
#>          [,1]      [,2]      [,3]
#> [1,] 1.033705 0.8485711 0.4207487
#> [2,] 6.726114 9.3822327 8.1679370
#> [3,] 5.306590 9.3782245 4.1482037
#> 
#> , , 2
#> 
#>          [,1]      [,2]     [,3]
#> [1,] 5.049821 7.3656464 8.389033
#> [2,] 5.079415 0.9890211 9.740383
#> [3,] 1.627842 3.4581040 1.484080
#> 
#> , , 3
#> 
#>            [,1]      [,2]      [,3]
#> [1,]  3.8929015 3.2630450 2.8199947
#> [2,] -0.1752263 8.2057809 4.3765055
#> [3,]  6.2808863 0.6555158 0.6417155

FirstNeg <- function(Arry) {
  Indx <- which(Arry < 0)[1]
  IndxAdj <- Indx - 1
  DIMs <- dim(Arry)
  PerShlf <- DIMs[1] * DIMs[2]
  PerCol <- DIMs[1]
  S = IndxAdj %/% PerShlf + 1
  C = (IndxAdj %% PerShlf) %/% PerCol + 1
  R = (IndxAdj %% PerCol) + 1 
  c(Shelf = S, Col = C, Row = R)
}
FirstNeg(Arr)
#> Shelf   Col   Row 
#>     3     1     2

Arr2 <- array(runif(24, -1, 10), dim = c(4,3,2))
Arr2
#> , , 1
#> 
#>            [,1]      [,2]     [,3]
#> [1,]  2.9276885 0.8110647 5.899159
#> [2,]  9.5890845 7.9121136 8.288719
#> [3,]  0.4560920 8.5574714 2.133576
#> [4,] -0.8854402 4.6570994 6.339482
#> 
#> , , 2
#> 
#>           [,1]      [,2]       [,3]
#> [1,] 0.6551673 0.7952096  2.8399725
#> [2,] 9.7990065 9.3844599  4.5216687
#> [3,] 2.2671181 7.7435021  7.9143699
#> [4,] 0.2659248 9.7215669 -0.9218006
FirstNeg(Arr2)
#> Shelf   Col   Row 
#>     1     1     4

Arr3 <- array(runif(40, -1, 10), dim = c(4,5,2))
Arr3
#> , , 1
#> 
#>           [,1]     [,2]     [,3]     [,4]       [,5]
#> [1,] -0.838367 7.930457 6.812043 1.863300  4.0765122
#> [2,]  6.517438 7.644668 7.470306 8.449804  1.4054271
#> [3,]  9.226922 9.877924 8.756826 3.812368 -0.2747094
#> [4,]  2.029413 5.753482 5.876339 3.269592  2.0327113
#> 
#> , , 2
#> 
#>            [,1]     [,2]       [,3]     [,4]     [,5]
#> [1,]  2.4141921 7.310087  5.2995350 3.412111 2.560947
#> [2,] -0.5360692 2.168657  2.8570683 1.199742 7.065106
#> [3,]  1.0314081 8.546291  6.3919882 8.421775 2.740751
#> [4,]  1.0171055 3.429070 -0.7244461 9.686670 9.744307
FirstNeg(Arr3)
#> Shelf   Col   Row 
#>     1     1     1

Created on 2019-12-04 by the reprex package (v0.2.1)

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.