R: refactor code