refactor R code with ifelse and helper fns