January 2, 2016

rbind.fill for 1-dimensional tables in r

The problem

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))
  })
}

r code


Previous post
Using attr labels for ggplot In social sciences, variables often have long and informative labels. Mostly they are too long to put into variable names, and often you want to
Next post
Crowd-sourced evaluation - the steps. At the very least, it has to be clear what is anonymous, what is not, what the data can be used for. If the client makes any part of the process


This blog by Steve Powell is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License, syndicated on r-bloggers and powered by Blot.
Privacy Policy
.