R solution without closures