Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find row with lowest value in COLUMNA, return row's COLUMNB

Tags:

r

I have a feeling this is one of those stupidly easy things where I'm just not using a function I should be.

Here's the relevant part of the function:

min(DATASET$COLUMNNAME, na.rm = TRUE)

Right now, it reports the correct value from COLUMNNAME--the lowest value in that column. Great. However, what I really want it to do is look across the dataframe to that result's entry in column NAME and print that. It should not print the minimum value at all, just the entry in NAME for the row with COLUMNAME's minimum value.

Is the best way to do it to get the row number of that minimum value somehow, and return DATASET$NAME[row,] ?

like image 917
Blair Rohlfing Avatar asked Oct 11 '13 20:10

Blair Rohlfing


People also ask

How do you return the lowest value in a column?

To find the minimum value of a column, use the MIN() aggregate function; it takes the name of the column or expression to find the minimum value. In our example, the subquery returns the minimum value in the temperature column (subquery: SELECT MIN(temperature) FROM weather ).

How do you find the minimum value in a row?

Use min() function to find the minimum value over the index axis. 2) Get minimum values of every row : Use min() function on a dataframe with 'axis = 1' attribute to find the minimum value over the row axis.

How do you find the lowest value in a table?

The MIN() function returns the smallest value of the selected column. The MAX() function returns the largest value of the selected column.


2 Answers

Looking for this maybe:

DATASET$NAME[DATASET$COLUMNNAME == min(DATASET$COLUMNNAME)]

That is, you select NAME from DATASET, where COLUMNAME has the minimum value.

If you don't like repeating DATASET so many times, this is equivalent using with:

with(DATASET, NAME[COLUMNNAME == min(COLUMNNAME)])
like image 50
janos Avatar answered Oct 12 '22 23:10

janos


The function you are looking for is which.min:

> set.seed(123)
> df<-data.frame(name=sample(LETTERS[1:10]),value=sample(10))
> df
   name value
1     C    10
2     H     5
3     D     6
4     G     9
5     F     1
6     A     7
7     J     8
8     I     4
9     B     3
10    E     2
> df[which.min(df$value),]
  name value
5    F     1
> df$name[which.min(df$value)]
[1] F
Levels: A B C D E F G H I J
like image 42
mrip Avatar answered Oct 13 '22 01:10

mrip