Finished R file, not tested