0

I have this dataframe.

A <- c('x','y','y','x')
B <- c(2,4,3,4)
example <- data.frame(A, B)

I would like to return the highest value (B) for each group in A, ie. return 4 for x and 4 for y. Hoping someone could help me write R code to do this. I am a beginner and first time poster, I apologise if this is a silly question!

Zaw
  • 1,434
  • 7
  • 15
VS99
  • 13
  • 2
  • Does this answer your question? [Extract the maximum value within each group in a dataframe](https://stackoverflow.com/questions/25314336/extract-the-maximum-value-within-each-group-in-a-dataframe) – Tim Jun 14 '21 at 10:57

3 Answers3

4

You could use a tidyverse approach:

library(tidyverse)

result <- example %>%
  group_by(A) %>%
  summarise(maxvalue = max(B))

result

This groups your data by the value of column A, then finds the maximum value for each unique value in A. Output:

  A     maxvalue
  <fct>    <dbl>
1 x            4
2 y            4
Rory S
  • 1,278
  • 5
  • 17
1

Using aggregate from base R

aggregate(cbind(maxvalue = B) ~ A, example, max)

-ouptut

  A maxvalue
1 x        4
2 y        4
akrun
  • 874,273
  • 37
  • 540
  • 662
0

Another base R option using tapply + stack

with(
  example,
  rev(stack(tapply(B,A,max)))
)

gives

  ind values
1   x      4
2   y      4
ThomasIsCoding
  • 96,636
  • 9
  • 24
  • 81