1

I have a table of values corresponding to an annual series of years, and i wanna know the code for R to give me the year if the highest value?

library(dplyr) 
df<-tibble(value=c(10,20,30,20,40,60),year=c(2001,2001,2001,2002,2002,2002))
Vinícius Félix
  • 8,448
  • 6
  • 16
  • 32
  • 1
    Welcome to SO, Enzo De Gaspari Ramos! It really helps on Stack sites (and especially the [tag:r] tag) for questions to include/show a few things: (1) self-contained, reproducible question, including sample data (using `dput(.)`) and expected output; and (2) current code to demonstrate effort so far, including the literal warnings/errors text, if applicable. Please see https://stackoverflow.com/q/5963269, [mcve], and https://stackoverflow.com/tags/r/info for good discussion/examples of how to do this. Please read them then come back, [edit] your question, and add the missing components. Thanks! – r2evans Sep 17 '21 at 15:25

2 Answers2

1

We may use slice_max

library(dplyr)
df %>% 
   group_by(year) %>%
   slice_max(n = 1, order_by = value) %>%
   ungroup
akrun
  • 874,273
  • 37
  • 540
  • 662
0

I assume you have something like that

library(dplyr)
df <- tibble(
  value = c(10,20,30,20,40,60),
  year = c(2001,2001,2001,2002,2002,2002)
)

You could use group_by to group each year summarise and max functions to return the highest value.

df %>% 
  dplyr::group_by(year) %>% 
  dplyr:: summarise(max_value = max(value))
)

This will return that

# A tibble: 2 x 2
   year max_value
  <dbl>     <dbl>
1  2001        30
2  2002        60

Next time provide some sample of your data because I do not know if this solves your problem.