Legacy Python Code. Need to translate into R