[R] Can body() return a function's body intact, in order, and as characters ready for editing?

Duncan Murdoch murdoch.duncan at gmail.com
Sun Mar 6 11:44:35 CET 2011


On 11-03-05 8:20 PM, Kingsley G. Morse Jr. wrote:
> Is my understanding correct that the body()
> function currently can't return a function's body
> intact, in order, and as characters ready for
> editing?

Yes, that's not what body() returns.  You can get what you want by 
printing the result of body(), e.g.

capture.output(print(body(f)))

However, your use of paste below isn't going to work on multi-line 
functions.

Duncan Murdoch

>
> My testing and reading of body()'s help indicate
> that it can not.
>
> Here's what I'm seeing.
>
> Consider pasting
>
>      1+
>
> and a function containing
>
>      x^2
>
> together to get
>
>      1+x^2
>
> As you can see below, body() reports three
> elements, out of order.
>
>      >  f<-function(x) x^2; b<-body(f); paste("1+",b, sep="")
>      [1] "1+^" "1+x" "1+2
>
> I realize that this might be worked around with
> something like
>
>      >  f<-function(x) x^2; b<-do.call(paste,as.list(c(deparse(body(f)),sep=""))); paste("1+",b, sep="")
>      [1] "1+x^2"
>
> However, I'm asking a different question.
>
> Is my understanding correct that body() can't
> return a function's body intact, in order, and as
> characters ready for editing?
>
> Thanks,
> Kingsley
>
>> sessionInfo()
> R version 2.12.1 (2010-12-16)
> Platform: i486-pc-linux-gnu (32-bit)
>
> locale:
>   [1] LC_CTYPE=en_US       LC_NUMERIC=C         LC_TIME=en_US
>   [4] LC_COLLATE=en_US     LC_MONETARY=C        LC_MESSAGES=en_US
>   [7] LC_PAPER=en_US       LC_NAME=C            LC_ADDRESS=C
> [10] LC_TELEPHONE=C       LC_MEASUREMENT=en_US LC_IDENTIFICATION=C
>
> attached base packages:
> [1] stats     graphics  grDevices utils     datasets  methods   base
>
> other attached packages:
>   [1] optimx_0.88        setRNG_2009.11-1   minqa_1.1.13       Rcpp_0.9.2
>   [5] Rvmmin_2011-2.11   Rcgmin_2011-2.10   ucminf_1.0-5       BB_2011.2-1
>   [9] quadprog_1.5-3     numDeriv_2010.11-1 rgp_0.2-3          snowfall_1.84
> [13] snow_0.3-3         rrules_0.1-0       emoa_0.4-3
>
> loaded via a namespace (and not attached):
> [1] tcltk_2.12.1 tools_2.12.1
>
>> Sys.getlocale()
> [1] "LC_CTYPE=en_US;LC_NUMERIC=C;LC_TIME=en_US;LC_COLLATE=en_US;LC_MONETARY=C;LC_MESSAGES=en_US;LC_PAPER=en_US;LC_NAME=C;LC_ADDRESS=C;LC_TELEPHONE=C;LC_MEASUREMENT=en_US;LC_IDENTIFICATION=C"
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.



More information about the R-help mailing list