title: For Loop with Subset in R
body: <p>I have the following data in a csv file:</p>
  
  <pre><code>Date        Model      Color    Value   Samples
  6/19/2017   Gold       Blue     0.5     500
  6/19/2017   Gold       Red      0.0     449
  6/19/2017   Silver     Blue     0.75    1320
  6/19/2017   Silver     Blue     1.5     103
  6/19/2017   Gold       Red      0.7     891
  6/19/2017   Gold       Blue     0.41    18103
  6/19/2017   Copper     Blue     0.83    564
  6/19/2017   Silver     Pink     1.17    173
  6/19/2017   Platinum   Brown    0.43    793
  6/19/2017   Platinum   Red      0.71    1763
  6/19/2017   Gold       Orange   1.92    503
  </code></pre>
  
  <p>I use the <code>fread</code> function to create a data.table: </p>
  
  <pre><code>library(dplyr)
  library(data.table)
  
  df &lt;- fread("test_data.csv", 
                   header = TRUE,
                   fill = TRUE,
                   sep = ",")
  </code></pre>
  
  <p>I then subset the data by <code>Model</code>, as follows:</p>
  
  <pre><code>df_subset &lt;- subset(df, df$Model=='Gold' &amp; df$Value &gt; 0)
  </code></pre>
  
  <p>Then, I create some percentiles based on the <code>Color</code> variable, as follows:</p>
  
  <pre><code>df_subset[, .(Samples = sum(Samples),
      '50th'    = quantile(AvgValue, probs = c(0.50)),
      '99th'    = quantile(AvgValue, probs = c(0.99)),
      '99.9th'  = quantile(AvgValue, probs = c(0.999)), 
      '99.99th' = quantile(AvgValue, probs = c(0.9999))),
  by = Color]
  </code></pre>
  
  <p>Which gives the following output:</p>
  
  <pre><code>    Color Samples  50th   99th  99.9th  99.99th
  1:   Blue   18603 0.455 0.4991 0.49991 0.499991
  2:    Red    1340 0.975 1.2445 1.24945 1.249945
  3: Orange     503 1.920 1.9200 1.92000 1.920000
  </code></pre>
  
  <p>I'm trying to iterate through the list of <code>Model</code> values and output the associated percentile values for each <code>Model</code> value.</p>
  
  <p>I've tried the following (which fails):</p>
  
  <pre><code>models &lt;- unique(df$Model)
  
  for (model in models){
  
    df$model[, .(Samples = sum(Samples),
                  '50th'    = quantile(Value, probs = c(0.50)),
                  '99th'    = quantile(Value, probs = c(0.99)),
                  '99.9th'  = quantile(Value, probs = c(0.999)), 
                  '99.99th' = quantile(Value, probs = c(0.9999))),
              by = Color]
  }
  </code></pre>
  
  <p>The error message is:</p>
  
  <pre><code>Error in .(Samples = sum(Samples), `50th` = quantile(Value, probs = c(0.5)),  :  could not find function "."
  </code></pre>