Huy Nguyen
Huy Nguyen

Reputation: 61

How to select max value FOR THE FIRST TIME of a column

I have a data look like:

power = seq(1:10)
Rsq = c(-0.503268561,-0.337920056,-0.000470763,0.204181075,0.299591119,0.376839371,0.424761718, 0.424487633, 0.642269314, 0.194640766)
df = data.frame(power,Rsq)

Now, I want to choose max value FOR THE FIRST TIME in the column 'Rsq'. From that, my expected result look like:

power ------- Rsq

7 ----------0.424761718

Upvotes: 0

Views: 59

Answers (2)

akrun
akrun

Reputation: 887118

We can get the difference of adjacent elements in 'Rsq', check if it is less than 0 and get the index of the max

library(dplyr)
df %>%
    slice(which.max(c(diff(Rsq), NA) < 0))
#   power       Rsq
#1     7 0.4247617

Upvotes: 1

Daniel O
Daniel O

Reputation: 4358

In Base-R

  df[which.max(df$Rsq),]

  power       Rsq
7     7 0.4247617

Upvotes: 0

Related Questions