R functions written by me (unless otherwise indicated in script)