Question

This is probably very simple, but I'm missing the correct syntax in order to simplify it.

Given a matrix, find the entry in one column which is the lowest value, greater than some input parameter. Then, return an entry in a different column on that corresponding row. Not very complicated... and I've found something that works but, a more efficient solution would be greatly appreciated.

I found this link:Better way to find a minimum value that fits a condition?

which is great.. but that method of finding the least entry loses the index information required to find a corresponding value in a corresponding row.

Let's say column 2 is the condition column, and column 1 is the one I want to return.... currently I've made this: (note that this only works because row two is full of numbers which are less than 1).

matrix[which.max((matrix[,2]>threshhold)/matrix[,2]),1]

Any thoughts? I'm expecting that there is probably some quick and easy function which has this effect... it's just never been introduced to me haha.

Was it helpful?

Solution 2

You could try the following. Say,

df <- matrix(sample(1:35,35),7,5)
> df
     [,1] [,2] [,3] [,4] [,5]
[1,]   18   16   27   19   31
[2,]   24    1    7   12    5
[3,]   28   35   23    4    6
[4,]   33    3   25   26   15
[5,]   14   10   11   21   20
[6,]    9    2   32   17   13
[7,]   30    8   29   22   34

Say your threshold is 5:

apply(df,2,function(x){ x[x<5] <- max(x);which.min(x)})
[1] 6 7 2 2 2

Corresponding to the values:

[1]  9  8  7 12  5

This should give you the index of the smallest entry in each column greater than threshold according to the original column indexing.

OTHER TIPS

rmk's answer shows the basic way to get a lot of info out of your matrix. But if you know which column you're testing for the minimum value (above your threshold), and then want to return a different value in that row, maybe something like

incol<- df[,4] # select the column to search
outcol <- 2 # select the element of the found row you want to get
threshold <- 5
df[ rev(order(incol>threshold))[1] ,outcol]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top