How to mutate by groups?

Viewed 2249

I am trying to mutate a new variable depending on the mean function of each group. I tried running this code using the pre-loaded data frame "ToothGrowth" available in R.

Output Results are incorrect, seems like it is looping the means of each group as a list instead of assigning to each group.

A diagram showing what I am trying to achieve:

image of what I am trying to achive, How to mutate by groups?

data("ToothGrowth")
head(ToothGrowth)

tg.tb01<-ToothGrowth %>% 
group_by(supp, dose) %>% # mydata has 3 more variables. 
  summarise(mean = mean(len)) %>% 
  print()
ToothGrowth %>% 
  group_by(supp) %>%
  mutate(submean2 = len - tg.tb01$mean/tg.tb01$dose)
2 Answers

You don't need another dataset to store the average. Look below:

library(dplyr)
library(datasets)

ToothGrowth %>% 
  group_by(supp, dose) %>%
  mutate(lenmean = mean(len),
         submean2 = len - lenmean/dose)

#> # A tibble: 60 x 5
#> # Groups:   supp, dose [6]
#>      len supp   dose lenmean submean2
#>    <dbl> <fct> <dbl>   <dbl>    <dbl>
#>  1   4.2 VC      0.5    7.98   -11.8 
#>  2  11.5 VC      0.5    7.98    -4.46
#>  3   7.3 VC      0.5    7.98    -8.66
#>  4   5.8 VC      0.5    7.98   -10.2 
#>  5   6.4 VC      0.5    7.98    -9.56
#>  6  10   VC      0.5    7.98    -5.96
#>  7  11.2 VC      0.5    7.98    -4.76
#>  8  11.2 VC      0.5    7.98    -4.76
#>  9   5.2 VC      0.5    7.98   -10.8 
#> 10   7   VC      0.5    7.98    -8.96
#> # ... with 50 more rows

If I understand correctly you should use instead. Please specify your desired output with numbers.

tg.tb01<-ToothGrowth %>% 
    group_by(supp, dose) %>%
    mutate(mean = mean(len)) %>%
    ungroup() %>%
    group_by(supp) %>%
    mutate(submean2 = len - mean/dose)
Related