Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return row of Data Frame based on value in a column - R

Tags:

r

My R data.frame df looks like:

     Name     Amount 1    "A"      150 2    "B"      120 3    "C"      "NA" 4    "D"      160 . . . 

I want to get the Name and Amount row when I do something like min(df$Amount).

That gets me the minimum number in the Amount column, but how do I get the Name in that same row? Or the entire row for that matter?

Name should be "B" in this case.

Similar to Select * Where Amount = min(Amount)

What is the best way to do this in R?

like image 209
brno792 Avatar asked Jul 18 '14 18:07

brno792


People also ask

How do I find rows with specific values in R?

You can use the following basic syntax to find the rows of a data frame in R in which a certain value appears in any of the columns: library(dplyr) df %>% filter_all(any_vars(. %in% c('value1', 'value2', ...)))

How do I convert data from column to row in R?

Data Visualization using R Programming Thus, to convert columns of an R data frame into rows we can use transpose function t. For example, if we have a data frame df with five columns and five rows then we can convert the columns of the df into rows by using as. data. frame(t(df)).

How do I get corresponding values in R?

To find the row corresponding to a nearest value in an R data frame, we can use which. min function after getting the absolute difference between the value and the column along with single square brackets for subsetting the row.


2 Answers

@Zelazny7's answer works, but if you want to keep ties you could do:

df[which(df$Amount == min(df$Amount)), ] 

For example with the following data frame:

df <- data.frame(Name = c("A", "B", "C", "D", "E"),                   Amount = c(150, 120, 175, 160, 120))  df[which.min(df$Amount), ] #   Name Amount # 2    B    120  df[which(df$Amount == min(df$Amount)), ] #   Name Amount # 2    B    120 # 5    E    120 

Edit: If there are NAs in the Amount column you can do:

df[which(df$Amount == min(df$Amount, na.rm = TRUE)), ] 
like image 112
Kara Woo Avatar answered Sep 30 '22 14:09

Kara Woo


Use which.min:

df <- data.frame(Name=c('A','B','C','D'), Amount=c(150,120,175,160)) df[which.min(df$Amount),]  > df[which.min(df$Amount),]   Name Amount 2    B    120 

From the help docs:

Determines the location, i.e., index of the (first) minimum or maximum of a numeric (or logical) vector.

like image 40
Zelazny7 Avatar answered Sep 30 '22 14:09

Zelazny7