I need to create a table from the source table (both below).
In the source table, we have families A and B, and the members of each family are indicated by the PESS column. Beneficiary members of each family are marked with the number 1 in the BEN column. From this table I need to create a new table in which you should have 2 more columns. Taking family A as an example, members 1 and 4 are the beneficiaries. Then, family A should be doubled into two groups with one beneficiary at a time (column I_BPC_FAM2). The FAM2 column indicates the groups.
With the code below, I am creating a new table, however the column I_BPC_FAM2 is missing. The problem must be resolved in R.
Is it possible to complete this code to get to the final table?
library(tidyverse)
tabela<-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<- summarise(group_by(tabela,FAM),contador=sum(BEN),cont=n())
tab2<-NULL
for(i in 1:length(tabela1$FAM)){
x<-as.numeric(tabela1[i,"contador"])
j<-as.numeric(tabela1[i,"cont"])
for(l in 1:x){
for(k in 1:j){
tab<-data.frame(tabela1[i,"FAM"],PESS=as.numeric(k),FAM2=as.numeric(l))
tab2<-rbind(tab2,tab)
final<-merge(tab2,tabela,by=c("FAM","PESS"))
final <- final[order(final$FAM, final$FAM2), ]
}
}
}
Original table:
> 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
The table generated by my code
> 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
Table I need to generate
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