Home > Back-end >  How to get the date of a max value from another column in R?
How to get the date of a max value from another column in R?

Time:11-05

Date Temperature Precipitation
15/01/2007 8 1.196
16/01/2007 7 1.218
17/01/2007 8 1.205
18/01/2007 4 1.157

This is a similar df to the one I'm working on.

I tried this:

df[which(df$Date == "max(df$P)")] 

and I got this "data frame with 0 columns and 20454 rows"

Then I tried this:

which(df$Date == "max(df$P)")

And I got this, with way more rows, and I'm sure there is a TRUE somewhere in those 20k rows

[1] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
  [13] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
  [25] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE

Then this one

df[max(df$P),)]

worked, but it showed the whole row, I am sure there should be another way to output just the date. Thanks in advance.

CodePudding user response:

Using which.max you could do:

df[which.max(df$P), "Date"] 
#> [1] "16/01/2007"

DATA

df <- data.frame(
  stringsAsFactors = FALSE,
              Date = c("15/01/2007", "16/01/2007", "17/01/2007", "18/01/2007"),
       Temperature = c(8L, 7L, 8L, 4L),
     Precipitation = c(1.196, 1.218, 1.205, 1.157)
)
  •  Tags:  
  • r
  • Related