Py code optomization and R code placed into functions