Nicky
Nicky

Reputation: 73

R - How to get value from a column based on value from another column of same row

I have a data frame (df) with 8 columns and 1200 rows. Among those 8 columns I want to find the minimum value of column 7 and find the corresponding value of column 2 in that particular row where the minimum value of column 7 was found. Also column 2 holds characters so I want a character vector giving me its value.

I found the minimum of column 7 using

min_val <- min(as.numeric(df[, 7]), na.rm = TRUE)

Now how do I get the value from column 2 (variable name of column being 'column.2') corresponding to the row in which column 7 contains value of 'min_val' as calculated above?

This might be a trivial question but I am new to R so any help will be much appreciated.

Upvotes: 3

Views: 22965

Answers (2)

The same answer from juba, but using data.table package (his answer uses just the R base, without the need of loading any libraries).

# Load data.table
library(data.table)

# Get 2nd column's value correspondent to the first minimum value in 7th column 
df[which.min(V7), V2]

# Get all respective values in 2nd column correspondent to the minimum value in 7th column 
df[V2 == min(V7), V2]

For handling data.frame-like objects, data.table is quite handly and helpful, just like the dplyr package. It's worth to look at them.

Here I've assumed your colnames were named as V1..V8. Otherwise, just replace the V7/V2 with the respective column names in 7th and 2nd position of your data, respectively.

Upvotes: 2

juba
juba

Reputation: 49033

Use which.min to get the minimum value index. Something like :

df[which.min(df[,7]),2]

Note that which.min only returns the first index of the minimum, so if you've got several rows with the same minimal value, you will only get the first one.

If you want to get all the minimum rows, you can use :

df[which(df[,7]==min(df[,7])), 2]

Upvotes: 8

Related Questions