Rendy Eza Putra
Rendy Eza Putra

Reputation: 101

How to Find Lowest Value Higher than 0 and Also Return The Matrix Row Index?

I want to find the lowest value excluding 0, and here is my code:

A = 600000000
B = 450000000
C = 300000000
D = 150000000
E = 90000000
F = 60000000
G = 30000000
H = 15000000
rpl.list <- matrix(c(A,B,C,D,E,F,G,H),ncol=1)
apply(rpl.list, 2, FUN = function(x) {min(x[x > 0])})

the result is:

[1] 1.5e+07

and the value is in rpl.list[8], I want to get the "8" value which is the row number of that value. How to get it? I know I can loop the rpl.list to find the exact same value with the result and return the i, like this:

for(i in 1:nrow(rpl.list)){
    if(rpl.list[i] == apply(rpl.list, 2, FUN = function(x) {min(x[x > 0])})){
        temp = i
    }
}

I wonder if there is a simple way to return the row number

Upvotes: 2

Views: 65

Answers (2)

milan
milan

Reputation: 4980

Remove all values less than or equal to zero, and then sort the remaining values. Find which value in your data matches the smallest value, and give its index.

which(rpl.list==sort(rpl.list[rpl.list>0])[1])

Upvotes: 1

akrun
akrun

Reputation: 887501

We can use which.min after replacing the values less than or equal to 0 to NA

which.min(replace(rpl.list, rpl.list <= 0, NA))

Upvotes: 4

Related Questions