Updated C++ code to work directly on R objects