R solution using self-modifying code