[Rd] Evaluate part of an expression at C level
Gábor Csárdi
c@@rd|@g@bor @end|ng |rom gm@||@com
Fri Sep 27 13:17:25 CEST 2019
Yes, you can manipulate the language object, and replace the the 1:10
with its own 5. element, and then call eval on the modified
expression. This can be simple if you know the structure of the
expression well, and difficult otherwise.
It goes like this:
SEXP lang_test(SEXP expr, SEXP idx, SEXP idxcall, SEXP env) {
SEXP idxcall2 = PROTECT(duplicate(idxcall));
SEXP expr2 = PROTECT(duplicate(expr));
SETCADR(idxcall2, CADR(expr));
SETCADDR(idxcall2, idx);
SEXP elem = PROTECT(Rf_eval(idxcall2, env));
SETCADR(expr2, elem);
SEXP result = PROTECT(Rf_eval(expr2, env));
UNPROTECT(4);
return result;
}
You need to add some type and index checking, to make sure that expr
is a language object and has the proper length, etc.
You can call it like this:
langtest <- function(expr, idx) {
.Call(c_lang_test, expr, idx, as.call(list(`[`, 1:10, 1)), environment())
}
We pass an indexing call to do the indexing, for simplicity, this also
supports S3 dispatch, etc.
Gabor
On Fri, Sep 27, 2019 at 11:35 AM Morgan Morgan
<morgan.emailbox using gmail.com> wrote:
>
> Hi,
>
> I am wondering if the below is possible?
> Let's assume I have the following expression:
>
> 1:10 < 5
>
> Is there a way at the R C API level to only evaluate the 5th element (i.e 5
> < 5) instead of evaluating the whole expression and then select the 5th
> element in the logical vector?
>
> Thank you
> Best regards
> Morgan
>
> [[alternative HTML version deleted]]
>
> ______________________________________________
> R-devel using r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-devel
More information about the R-devel
mailing list