title: Find the average values by grouping and sub-grouping variables, and count of the number of times a value occurs within these groups in R
body: <p>I have a dataset which has four columns of data. </p>
  
  <p>I want to group the rows by two variables, and the columns by one variable</p>
  
  <p>Here is an example of my data</p>
  
  <pre><code>df &lt;- data.frame(
  Price = rnorm(24), 
  Grouping = rep(c("CD", "NW", "SMK", "ghd"),6),
  Sub_grouping = c("CDapple", "NWapple", "SMKapple", "ghdapple",
                 "CDPear", "NWpear", "SMKpear", "ghdpear",
                 "CDgrape",  "NWgrape", "SMKgrape", "ghdgrape",
                 "CDapple", "NWapple", "SMKapple", "ghdapple",
                 "CDPear", "NWpear", "SMKpear", "ghdpear",
                 "CDgrape",  "NWgrape", "SMKgrape", "ghdgrape"),
  SP = rep(c("SP", "OffSP"),12))
  </code></pre>
  
  <p>To get the average of the Price variable for each subgroup, I can run the following:</p>
  
  <pre><code>df &lt;- melt(df)
  df_mean &lt;- dcast(df, Grouping + Sub_grouping ~ SP, value.var = "value",  fun.aggregate = mean)
  </code></pre>
  
  <p>I would also like the average value of Price for each grouping variable. Is this possible?</p>
  
  <p>I also would like to count the number of values for Price which feed into each average Price. So for each Group, by SP and OffSP, the number of prices which feed into this; and for each sub_group, by SP and OffSP, the number of prices which feed into this. </p>
  
  <p>Does anyone know how to do this?</p>
  
  <p>I've seen these questions <a href="https://stackoverflow.com/questions/30592041/create-a-column-with-a-count-of-occurrences-in-r">Create a column with a count of occurrences in R</a>  <a href="https://stackoverflow.com/questions/27477232/how-can-i-count-the-number-of-instances-a-value-occurs-within-a-subgroup-in-r">How can I count the number of instances a value occurs within a subgroup in R?</a>
  But their contingency tables are 2x2, and I need a table with grouping and sub-group as rows, with SP / OffSP as columns. </p>
  
  <p>Thanks</p>