0

I am new to stackoverflow which is why I am asking a question instead of commenting on the post I am having problems with: Using Dplyr's to find max values of a group and mutate the result in another column in the same table

The problem I am having (which is the same problem I have with my own dataset) is that the grouping does not seem to be working. When I run the example code as follows

df <- tibble(a = rep(letters[1:3], each = 3), b = seq(0.1,0.9, length.out = 9))
 
 
df %>% 
    group_by(a) %>% 
    mutate(group_max = max(b)) %>% 
    ungroup()

I receive the following output:


 A tibble: 9 × 3
  a         b group_max
  <chr> <dbl>     <dbl>
1 a       0.1       0.9
2 a       0.2       0.9
3 a       0.3       0.9
4 b       0.4       0.9
5 b       0.5       0.9
6 b       0.6       0.9
7 c       0.7       0.9
8 c       0.8       0.9
9 c       0.9       0.9

Output should be:

 A tibble: 9 x 3
   a         b group_max
   <chr> <dbl>     <dbl>
 1 a       0.1       0.3
 2 a       0.2       0.3
 3 a       0.3       0.3
 4 b       0.4       0.6
 5 b       0.5       0.6
 6 b       0.6       0.6
 7 c       0.7       0.9
 8 c       0.8       0.9
 9 c       0.9       0.9

This is what I'm currently working with (in case this helps)

> R.version
               _                                
platform       x86_64-w64-mingw32               
arch           x86_64                           
os             mingw32                          
crt            ucrt                             
system         x86_64, mingw32                  
status                                          
major          4                                
minor          2.1                              
year           2022                             
month          06                               
day            23                               
svn rev        82513                            
language       R                                
version.string R version 4.2.1 (2022-06-23 ucrt)
nickname       Funny-Looking Kid 

Any help would be greatly appreciated!

jux
  • 1
  • 1
  • 2
    Use `dplyr::mutate`. Maybe your `mutate` got masked by `plyr::mutate` i.e. `df %>% group_by(a) %>% dplyr::mutate(group_max = max(b)) %>% ungroup()` – akrun Sep 05 '22 at 17:50
  • 1
    `I am new to stackoverflow which is why I am asking a question instead of commenting on the post` ... you are supposed to ask your own question ... you do not put questions about your own problem in comments to someone else's question – jsotola Sep 05 '22 at 17:51
  • And thank you @jsotola, I'm trying to read all the guidelines and follow accordingly, but there are still things I'm not sure about. Thank you for clarifying! – jux Sep 05 '22 at 18:31

0 Answers0