Skip to content

env argument not used to actually source the R code #851

@filipsch

Description

@filipsch

If you set the env variable in sourceCpp, Rcpp correctly makes the R functions and modules available in the specified environment. However, the R snippet in the /*** R block is not executed in this same environment. This causes unexpected errors.

Reproducible example

test.rcpp

#include <Rcpp.h>
using namespace Rcpp ;

// [[Rcpp::export]]
int answer(){
    return 42 ;
}

/*** R
    # call answer and check you get the right result
    x <- answer()
    x
*/

Next, in R:

library(Rcpp)
testEnv <- new.env()
sourceCpp("test.cpp", env = testEnv)
ls(testEnv)

Expected output:

> library(Rcpp)
> testEnv <- new.env()
> sourceCpp("test.cpp", env = testEnv)

>     # call answer and check you get the right result
>     x <- answer()

>     x
[1] 42
> ls(testEnv)
[1] "answer" "x"

Actual output:

> library(Rcpp)
> testEnv <- new.env()
> sourceCpp("test.cpp", env = testEnv)

>     # call answer and check you get the right result
>     x <- answer()
Error in answer() : could not find function "answer"
> ls(testEnv)
[1] "answer"

Context

I work at DataCamp, where we're building a course on Rcpp together with Romain Francois. Our R execution backend heavily relies on the concept of environments: we run the solution code in a solution environment and the student code in a student environment, so that we can check the equality of objects. Because of the above, it is currently very hard for Rcpp exercise to do this. For even more context, you can check out this issue.

Potential solution

I think that passing local = env to the source() call here fixes this, as done here. Before doing a PR, I wanted to know whether the current behavior is intended and what the authors' take on it is.

cc @sumedh10

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions