سؤال

Sourcing a file containing cppFunction function does not compile/load the function. Below is the code with two functions one wrapped as string in a R function.

cat('
rcpp_iter <- function() 
{ 
  Rcpp::cppFunction(\'NumericVector func0_with_RString(NumericVector  df1,NumericVector  df2){ 
int N1 = df1.size(); 
NumericVector df3(N1); 
df3[0]=df2[0]; 

for(int i=1;i<N1;++i) 
{df3[i]=df2[i-1]+df1[i];} 

return df3; 
} 
\') 
} 


  Rcpp::cppFunction(\'NumericVector func0(NumericVector  df1,NumericVector  df2){ 
int N1 = df1.size(); 
NumericVector df3(N1); 
df3[0]=df2[0]; 

for(int i=1;i<N1;++i) 
{df3[i]=df2[i-1]+df1[i];} 

return df3; 
} 
\') 

',file='testcpp.r')
source('testcpp.r')

set.seed(100);x=sample(1:100,10)
flag0 <- c(1,0,0,1,1,1,0,0,1,0)

rcpp_iter();func0_with_RString(flag0,x) does not work

func0(flag0,x) works

Why doesn't func0_with_RString work after invoking rcpp_iter?

هل كانت مفيدة؟

المحلول

The answer to your question is concordant with the answer to: Why x is not found in the example below?

f <- function() {
   x <- 10
}

f()
print(x)
## Error: object 'x' not found

Look at the env arg of RCpp:cppFunction. You may e.g. pass env=globalenv() to bind func0_with_RString in the global environment. But this is definitely not the right way to define a function (unless you're just curious). Refer to @DirkEddelbuettel's comments on the matter.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top