carvalhosantos
carvalhosantos

Reputation: 57

How to find max values in each group in R using dplyr

How could I generate a new summary data.frame with only the largest values of a data.frame

I tried the code below, but the result was not what I expected.

n<-c('A','B','C','A','B','C','A','B','C')
x1<-c(1,2,3,4,5,6,7,8,9)
x2<-c(9,8,7,4,5,6,1,2,3)

df<-data.frame(n, x1, x2)


df%>%
  group_by(n)%>%
  mutate('x1'=max('x1'), 'x2'=max('x2'))

i wanted this

n   X1  X2
A   7   9
B   8   8
C   9   7

Upvotes: 0

Views: 274

Answers (4)

ThomasIsCoding
ThomasIsCoding

Reputation: 101024

A data.table option

library(data.table)
setDT(df)[, Map(max, .SD), n]

gives

   n x1 x2
1: A  7  9
2: B  8  8
3: C  9  7

Upvotes: 0

Baraliuh
Baraliuh

Reputation: 2141

Just change it to x1 = max(x1) without the quotes and change mutate into summarise.

df%>%
    group_by(n)%>%
    summarise(x1=max(x1), x2=max(x2))

Upvotes: 3

akrun
akrun

Reputation: 886938

We can use across with group_by

library(dplyr)
df %>%
    group_by(n) %>%
    summarise(across(everything(), max, na.rm = TRUE))

-output

# A tibble: 3 x 3
  n        x1    x2
  <chr> <dbl> <dbl>
1 A         7     9
2 B         8     8
3 C         9     7

Or use aggregate in base R

aggregate(.~ n, df, max)

Upvotes: 2

Karthik S
Karthik S

Reputation: 11584

Does this work:

library(dplyr)
df %>% group_by(n ) %>% summarise(across(x1:x2, max))
# A tibble: 3 x 3
  n        x1    x2
  <chr> <dbl> <dbl>
1 A         7     9
2 B         8     8
3 C         9     7

Upvotes: 4

Related Questions