0

I am trying to get the corresponding value of the cell in R but unable to do so. My df has basically 2 columns. Date and Price for a set of 5 observations. I want to know at which date was the price the maximum.

I wrote the below code but it only shows Date

HH <- max(df$price, show = "Date")

HH

[1] Date
roschach
  • 8,390
  • 14
  • 74
  • 124
Emjee11
  • 1
  • 1
  • 1
    Welcome to StackOverflow! Please share your data using `dput(df)` – s_baldur Dec 10 '18 at 17:13
  • Please read [(1)](https://stackoverflow.com/help/how-to-ask) how do I ask a good question, [(2)](https://stackoverflow.com/help/mcve) how to create a MCVE as well as [(3)](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example#answer-5963610) how to provide a minimal reproducible example in R. Then edit and improve your question accordingly. I.e., abstract from your real problem... – Christoph Dec 10 '18 at 17:16

3 Answers3

1

I suggest something like:

df$date[df$price == max(df$price)]

You might read this as show me the value for df$date such that the value for df$price is the maximal value in the price column. Use the $ operator to select a column, read the [ and ] as 'such that' and note the == sign is not = as == means 'is equal too' and = (or <-) would be used to assign a value to a variable. Your answer should be the date at which the price was maximal.

massisenergy
  • 1,764
  • 3
  • 14
  • 25
0

I think this is what you want; which.max gives the index of the maximum value in a vector.

df <- data.frame(date = 1:5, price = 6:10)
df
#>   date price
#> 1    1     6
#> 2    2     7
#> 3    3     8
#> 4    4     9
#> 5    5    10
df$date[which.max(df$price)]
#> [1] 5

Created on 2018-12-10 by the reprex package (v0.2.0).

Calum You
  • 14,687
  • 4
  • 23
  • 42
0

I'm not sure if this is the quickest way but this can be done in dplyr

    library(tidyverse)
    test <- data.frame(date = as.Date(c("2018-01-01","2018-01-02","2018-01-03", "2018-01-04", "2018-01-05")),
                       price = c(20, 35, 21, 39, 40))
answer <- test %>%
  filter(price == max(test$price))
CMH89
  • 107
  • 1
  • 10