I have two one-dimensional frequency tables resulting from say the baseline and endline of a survey, recording say membership of 5 age groups. The levels of the two variables should be the same but they might not be, say if at endline there was no-one in one of the age groups.
0-10 | 11-20 | 21-30 | |
---|---|---|---|
baseline | 3 | 9 | 22 |
endline | 0 | 6 | 12 |
I want to merge these into one table. The data comes out of some survey software so the two variables aren’t factors. The endline variable doesn’t know there is a missing level, so the one-dimensional frequency table is just this:
11-20 | 21-30 |
---|---|
6 | 12 |
I know of no elegant way to do this. You can only use rbind if the names of the two tables are the same. If the two tables were data.frames, you could use rbind.fill
from plyr
, otherwise a nice function but not helpful in the one-dimensional case.
In the end I wrote a function:
rbind1dtable=function(tab1,tab2,fail=0){
sapply(union(names(tab1),names(tab2)),function(n){
t1=tab1[which(names(tab1)==n)]
t2=tab2[which(names(tab2)==n)]
c(ifelse(length(t1)==0,fail,t1),ifelse(length(t2)==0,fail,t2))
})
}