Home > Back-end >  How to print out max in R?
How to print out max in R?

Time:03-19

ID before after difference  
 3    154    150   4  
 4    156    150   6 
 5    160    157   3   
 6    170    163   7   
 7    150    149   1 
 8    160   158    2

Above is my data.
I need to print out ID that has the biggest difference (but I have to print only ID number, not the other values).
How can I do that in R??

CodePudding user response:

With base R:

df$ID[which.max(df$difference)]

#[1] 6

Data

df <- structure(list(ID = 3:8, before = c(154L, 156L, 160L, 170L, 150L, 
160L), after = c(150L, 150L, 157L, 163L, 149L, 158L), difference = c(4L, 
6L, 3L, 7L, 1L, 2L)), class = "data.frame", row.names = c(NA, 
-6L))

CodePudding user response:

With dplyr package we could use slice_max and then pull(ID). You will get a vector:

library(dplyr)

df %>% 
  slice_max(difference) %>% 
  pull(ID)

output:

[1] 6

data:

df <- structure(list(ID = 3:8, before = c(154L, 156L, 160L, 170L, 150L, 
160L), after = c(150L, 150L, 157L, 163L, 149L, 158L), difference = c(4L, 
6L, 3L, 7L, 1L, 2L)), class = "data.frame", row.names = c(NA, 
-6L))

CodePudding user response:

#This is a dataframe of example
a <- dataframe(id = c(1, 2), dif = c(4, 5))

#This is the solution with Rbase
a[a$dif==max(a$dif), "id"]

  •  Tags:  
  • r
  • Related