[R] Modify base R functions in Rprofile.site

Yihui Xie xieyihui at gmail.com
Mon Oct 5 00:07:05 CEST 2009


Thanks a lot, Charlie. What a coincidence -- I'm also working on
Sweave functions. parse() and deparse() can make the code more tidy
(they are used in source() and RweaveLatexRuncode()),

> RweaveLatex
function ()
{
    list(setup = RweaveLatexSetup, runcode = RweaveLatexRuncode,
        writedoc = RweaveLatexWritedoc, finish = RweaveLatexFinish,
        checkopts = RweaveLatexOptions)
}
<environment: namespace:utils>

but we can either (1) let R automatically 'tidy up' our code and
remove all the comments or (2) keep the comments but leave the
original code untouched.

I worked out a trick to preserve the comments while tidying up the R
code, and I want to replace parse() and deparse() with my customized
functions, in which case Sweave will keep the comments.

However, my functions will need base::parse() and base::deparse() to
help me, therefore my real difficulty is, how to let Sweave use my
functions to parse and deparse R code without really modifying them in
the base enviroment? I'm using the command 'R CMD Sweave'. If there is
no neat approach, I'll change my question to: how to write a package,
say, Sweave2, that can be run using command line 'R CMD Sweave2 file'?

Regards,
Yihui
--
Yihui Xie <xieyihui at gmail.com>
Phone: 515-294-6609 Web: http://yihui.name
Department of Statistics, Iowa State University
3211 Snedecor Hall, Ames, IA



2009/10/4 cls59 <chuck at sharpsteen.net>:
>
>
>
> Yihui Xie wrote:
>>
>> Hi everyone,
>>
>> I want to modify two base R functions 'parse' and 'deparse'
>> immediately after R has started, so I added some code in the file
>> 'Rprofile.site' under the 'etc' directory. Here is a simple example:
>>
>> parse=function(...){
>>     base::parse(...)
>> }
>>
>> I'll get an error when I start R as follows:
>>
>> Error: cannot change value of locked binding for 'parse'
>>
>> Is there a solution for my problem? Please note that I *have to*
>> override the function names. Thanks very much!
>>
>>
>
>
> Hi Yihui,
>
> I have had cause to do some some similar things to Sweave functions-- maybe
> the following will help:
>
>  # Find out where the function lives.
>  env <- as.environment( 'package:base' )
>
>  # Crack the binding.
>  unlockBinding( 'parse', env )
>
>  # Replace the function.
>  assignInNamespace( 'parse', function(...){
>
>   # Your function here, or an object that contains it.
>
>   }, ns = 'base' )
>
>  # Relock the binding.
>  lockBinding( 'parse', env )
>
>
> Note that the above is *very* dark voodoo-- it may cause unforeseen
> consequences.
>
> Good luck!
>
> -Charlie
>
> -----
> Charlie Sharpsteen
> Undergraduate
> Environmental Resources Engineering
> Humboldt State University




More information about the R-help mailing list