title: Frequency tables by groups with weighted data in R
body: <p>I wish to calculate two kind of frequency tables by groups with weighted data. </p>
  
  <p>You can generate reproducible data with the following code :</p>
  
  <pre><code>Data &lt;- data.frame(
       country = sample(c("France", "USA", "UK"), 100, replace = TRUE),
       migrant = sample(c("Native", "Foreign-born"), 100, replace = TRUE),
       gender = sample (c("men", "women"), 100, replace = TRUE),
       wgt = sample(100),
       year = sample(2006:2007)
       )
  </code></pre>
  
  <p>Firstly, I try to calculate a frequency table of migrant status (Native VS Foreign-born) by country and year. I wrote the following code using the packages <code>questionr</code> and <code>plyr</code> : </p>
  
  <pre><code>db2006 &lt;- subset (Data, year == 2006)
  db2007 &lt;- subset (Data, year == 2007)
  
  result2006 &lt;- as.data.frame(cprop(wtd.table(db2006$migrant, db2006$country, weights=db2006$wgt),total=FALSE))
  result2007 &lt;- as.data.frame(cprop(wtd.table(db2007$migrant, db2007$country, weights=db2007$wgt),total=FALSE))
  
  result2006&lt;-rename (result2006, c(Freq = "y2006"))
  result2007&lt;-rename (result2007, c(Freq = "y2007"))
  
  result &lt;- merge(result2006, result2007, by = c("Var1","Var2"))
  </code></pre>
  
  <p>In my real database, I have 10 years so it takes times to apply this code for all the years. Does anyone know a faster way to do it ?</p>
  
  <p>I also wish to calculate the share of women and men among migrant status by country and year. I am looking for something like :</p>
  
  <pre><code>Var1            Var2     Var3     y2006   y2007
  Foreign born    France   men        52     55
  Foreign born    France   women      48     45
  Native          France   men        51     52
  Native          France   women      49     48
  Foreign born    UK       men        60     65
  Foreign born    UK       women      40     35
  Native          UK       men        48     50
  Native          UK       women      52     50
  </code></pre>
  
  <p>Does anyone have an idea of how I can get these results?</p>