From armstrong.whit at gmail.com  Tue Apr 17 02:48:32 2012
From: armstrong.whit at gmail.com (Whit Armstrong)
Date: Mon, 16 Apr 2012 20:48:32 -0400
Subject: [Rd] eval a SYMSXP from C
In-Reply-To: <4F8CB2F3.8060802@gmail.com>
References: <CAMi=pg6-q5EOU1YHXiSqyjCvQ5vGtNNU2P8xjpr9sDB21nvzJw@mail.gmail.com>
	<4F8CB2F3.8060802@gmail.com>
Message-ID: <CAMi=pg6k0YmrOJxTjRM9atan2siOYfPZ8Y54Sj8AU74MC9ypwQ@mail.gmail.com>

Thanks, Duncan.

Your suggestion works.

And thanks for the hint, about the env.  I suppose I should preserve
the env of the original function where the substitute was called...

Cheers,
Whit


On Mon, Apr 16, 2012 at 8:01 PM, Duncan Murdoch
<murdoch.duncan at gmail.com> wrote:
> On 12-04-16 5:53 PM, Whit Armstrong wrote:
>>
>> Can someone offer some advice on how to properly evaluate a SYMSXP
>> from a .Call ?
>>
>> I have the following in R:
>>
>> variable xn, with an attribute "mu" which references the variable mu
>> in the global environment.
>>
>> I know "references" is a loose term; mu was defined in this fashion as
>> a way to implement deferred binding:
>>
>> foo<- function(x,mu) {
>> ? ? attr(x,"mu")<- substitute(mu)
>> ? ? x
>> }
>>
>> mu<- 2.0
>> xn<- foo(rnorm(100),mu)
>>
>>> typeof(attr(xn,"mu"))
>>
>> [1] "symbol"
>>>
>>> eval(attr(xn,"mu"))
>>
>> [1] 2
>>>
>>>
>>
>> In a .Call, I am attempting to eval the SYMSXP as follows:
>>
>> SEXP mu_ = Rf_getAttrib(x_,Rf_install("mu"));
>>
>> if(TYPEOF(mu_)==SYMSXP) {
>> ? mu_ = Rf_eval(Rf_lang1(mu_),R_GlobalEnv);
>> }
>>
>> However, when running this code, I get the following error:
>> Error in logp(xn) : could not find function "mu"
>>
>> Do I need to create an expression of c("get", "mu") to force the name
>> lookup to evaluate the SYMSXP?
>>
>
> Rf_lang1(mu_) will produce mu(), not mu. ?I think you just want to evaluate
> mu_.
>
> There are lots of possible types of object returned by substitute(mu), but
> you should be able to evaluate all of them. ?You probably don't want to
> evaluate them in R_GlobalEnv, you want to evaluate them in the environment
> where the call was made to foo, so that you'll get local variables if it was
> called from a function.
>
> Duncan Murdoch



[Rd] eval a SYMSXP from C
Whit Armstrong