Grouping Frame Values

Viewed 19

I have a dataset of ingredients for cookies. I'm trying to answer which group (A, B, C, etc) of cookies has the most sugar in them. The dataset is structured as follows:

 group    id    mois  prot  fat   hocolate sugar carb cal
1       A 14069 27.82 21.43 44.87 5.11   1.77 0.77 4.93
2       A 14053 28.49 21.26 43.89 5.34   1.79 1.02 4.84
3       A 14025 28.35 19.99 45.78 5.08   1.63 0.80 4.95
4       B 14016 30.55 20.15 43.13 4.79   1.61 1.38 4.74
5       B 14005 30.49 21.28 41.65 4.82   1.64 1.76 4.67
6       A 14075 31.14 20.23 42.31 4.92   1.65 1.40 4.67
7       C 14082 31.21 20.97 41.34 4.71   1.58 1.77 4.63
8       C 14097 28.76 21.41 41.60 5.28   1.75 2.95 4.72
etc....

How can I plot the mean of each grouping to show that one of them has a higher average of sugar than the others? Or at the least, how can I print off the results of the grouped averages of sugar to defend my argument that one has more sugar than the other?

1 Answers

After saving your text to CSV and loading this file into R, it's pretty easy to obtain the mean sugar quantity per group, which I'm assuming is what you need. You first group your data by variable group and then summarize the data using the "mean" function.

library(dplyr)

(cookies = df %>% 
  group_by(group) %>% 
  summarize(meanSugar = mean(sugar)))

  group meanSugar
  <chr>     <dbl>
1 A          1.71
2 B          1.62
3 C          1.66

As you can see, group A has sugar content a bit higher than the others based on your data. If you wanna go a step further and really plot this data, you can do that:

library(ggplot2)

cookies %>%
  ggplot(aes(x=meanSugar,y=reorder(group,meanSugar),fill=group,label=meanSugar)) + 
  geom_col()+
  labs(y="Cookie groups",x="Mean Sugar")+
  geom_label(stat="identity",hjust=+1.2,color="white")+
  theme(legend.position = "none")

Bar plot you need

If you have any questions on some of these steps, let me know!

Obs: please try to provide better data the next time so it's easy to reproduce what you need and give you a quick answer :)

Related