title: How to convert a string to a variable and to loop through group_by?
body: <p>Assume I have a dataset with two columns, Location and Product, that shows how many of each product is sold at each location. I create a contingency table for the number of each product sold at each location:</p>
  
  <pre><code>data%&gt;% 
    group_by(Location,Product)%&gt;%
    summarize(n=n()) %&gt;%
    pivot_wider(names_from = product, values_from = n) 
  </code></pre>
  
  <p>Now, imagine that instead of a single Product column, I have US_Product, Japan_Product,..., Germany_Product. How can I create my contingency tables in a for loop? 
  NOTE: when I create a vector of products like <code>p&lt;-c("Product1", "Product2",..., "Product3")</code> and loop through these products, I get an error message because these are strings and not variable names.</p>
  
  <p>Here is a minimal example:</p>
  
  <pre><code>Location &lt;- c("AB","ON","MN","AB","ON")
  Product1&lt;-c("Type1","Type2","Type1","Type3","Type1")
  Product2&lt;-c("Type3","Type2","Type3","Type3","Type2")
  Product3&lt;-c("Type1","Type2","Type1","Type1","Type1")
  data &lt;- tibble(Location,Product1,Product2,Product3)
  data%&gt;% 
    group_by(Location,Product1)%&gt;%
    summarize(n=n()) %&gt;%
    pivot_wider(names_from = Product1, values_from = n) #this works as expected
  
  #now I want to do the same thing in a loop
  prodV &lt;- c("Product1","Product2","Product3")
  for (i in c(1:3)){
    var &lt;- prodV[i]
    data%&gt;% 
      group_by(Location,var)%&gt;%
      summarize(n=n()) %&gt;%
      pivot_wider(names_from = var, values_from = n)   
  }
  </code></pre>