title: Create new duplicate table from another, adding new values from the originals, using R
body: <p>I need to create a table, from the original table (both below).</p>
  
  <p>In the original table, we have the families A and B, and the members of each family is indicated by the column PESS. The members of each family who are beneficiaries are marked by the number 1 in the BEN column.
  From this table, I need to generate a new table, in which you should have 2 more columns. Taking the family A as an example, members 1 and 4 are beneficiaries. Then, the family A should be doubled into two groups, with only one beneficiary at a time (column I_BPC_FAM2). The FAM2 column indicates the groups.</p>
  
  <p>With the code below, I am generating the new table, however, the <strong>I_BPC_FAM2</strong> column is missing. The problem must be solved in the R.</p>
  
  <p>Is it possible to complete this code to get to the final table?</p>
  
  <pre><code>library(tidyverse) 
  tabela&lt;-data.frame(FAM=c("A","A","A","A","B","B","B"), PESS=c(1,2,3,4,1,2,3),BEN=c(1,0,0,1,0,0,1))
  tabela1&lt;- summarise(group_by(tabela,FAM),contador=sum(BEN),cont=n()) #faz a tabela com contadores
  
  tab2&lt;-NULL
  for(i in 1:length(tabela1$FAM)){
      x&lt;-as.numeric(tabela1[i,"contador"])
      j&lt;-as.numeric(tabela1[i,"cont"])
      for(l in 1:x){
        for(k in 1:j){
           tab&lt;-data.frame(tabela1[i,"FAM"],PESS=as.numeric(k),FAM2=as.numeric(l))
           tab2&lt;-rbind(tab2,tab)
           final&lt;-merge(tab2,tabela,by=c("FAM","PESS"))
           final &lt;- final[order(final$FAM, final$FAM2), ] 
        }
     }  
   }
  </code></pre>
  
  <p>Original table:</p>
  
  <pre><code>&gt; tabela
    FAM PESS BEN
  1   A    1   1
  2   A    2   0
  3   A    3   0
  4   A    4   1
  5   B    1   0
  6   B    2   0
  7   B    3   1
  </code></pre>
  
  <p>Table generated by my code</p>
  
  <pre><code>&gt; final
     FAM PESS FAM2 BEN
  1    A    1    1   1
  3    A    2    1   0
  5    A    3    1   0
  7    A    4    1   1
  2    A    1    2   1
  4    A    2    2   0
  6    A    3    2   0
  8    A    4    2   1
  9    B    1    1   0
  10   B    2    1   0
  11   B    3    1   1
  </code></pre>
  
  <p>Table I need to generate</p>
  
  <pre><code>   FAM PESS FAM2 BEN I_BPC_FAM2
  1    A    1    1   1         1
  3    A    2    1   0         0
  5    A    3    1   0         0 
  7    A    4    1   1         0
  2    A    1    2   1         0
  4    A    2    2   0         0
  6    A    3    2   0         0
  8    A    4    2   1         1
  9    B    1    1   0         0
  10   B    2    1   0         0
  11   B    3    1   1         1
  </code></pre>