R functions to split up data, stack it, and reshape it