[R] recommended way to group function calls in Sweave

Duncan Murdoch murdoch.duncan at gmail.com
Wed Apr 25 15:41:01 CEST 2012


On 12-04-25 7:41 AM, Liviu Andronic wrote:
> Dear all
> When using Sweave, I'm always hitting the same bump: I want to group
> repetitive calls in a function, but I want both the results and the
> function calls in the printed output. Let me explain myself.
>
> Consider the following computation in an Sweave document:
> summary(iris[,1:2])
> cor(iris[,1:2])
>
> When using these two calls directly, I obtain the following output:
>> summary(iris[,1:2])
>    Sepal.Length    Sepal.Width
>   Min.   :4.300   Min.   :2.000
>   1st Qu.:5.100   1st Qu.:2.800
>   Median :5.800   Median :3.000
>   Mean   :5.843   Mean   :3.057
>   3rd Qu.:6.400   3rd Qu.:3.300
>   Max.   :7.900   Max.   :4.400
>> cor(iris[,1:2])
>               Sepal.Length Sepal.Width
> Sepal.Length    1.0000000  -0.1175698
> Sepal.Width    -0.1175698   1.0000000
>
>
> However, if I try to group the calls in a function:
> f<- function(d, ind){
>    print(summary(d[ , ind]))
>    print(cor(d[ , ind]))
>    return(invisible(NULL))
> }
>
>
> Then I get a different output in the Sweave PDF:
>> f(iris, 1:2)
>    Sepal.Length    Sepal.Width
>   Min.   :4.300   Min.   :2.000
>   1st Qu.:5.100   1st Qu.:2.800
>   Median :5.800   Median :3.000
>   Mean   :5.843   Mean   :3.057
>   3rd Qu.:6.400   3rd Qu.:3.300
>   Max.   :7.900   Max.   :4.400
>               Sepal.Length Sepal.Width
> Sepal.Length    1.0000000  -0.1175698
> Sepal.Width    -0.1175698   1.0000000
>
>
> Of course I can use 'echo=F' to remove the '>  f(iris, 1:2)' in the
> above, but how can I do to keep the original calls 'summary(d[ ,
> ind])' and 'cor(d[ , ind])'? Or even better, could the actual calls be
> used, after the replacement of arguments by their values:
> 'summary(iris[,1:2])' and 'cor(iris[,1:2])'.
>
> Or is the recommended way to use cat()-ed statements:
> f<- function(d, ind){
>    cat('Variable summary:\n')
>    print(summary(d[ , ind]))
>    cat('\nCorrelation table:\n')
>    print(cor(d[ , ind]))
>    return(invisible(NULL))
> }
>
>
> To obtain such output:
>> f(iris, 1:2)
> Variable summary:
>    Sepal.Length    Sepal.Width
>   Min.   :4.300   Min.   :2.000
>   1st Qu.:5.100   1st Qu.:2.800
>   Median :5.800   Median :3.000
>   Mean   :5.843   Mean   :3.057
>   3rd Qu.:6.400   3rd Qu.:3.300
>   Max.   :7.900   Max.   :4.400
>
> Correlation table:
>               Sepal.Length Sepal.Width
> Sepal.Length    1.0000000  -0.1175698
> Sepal.Width    -0.1175698   1.0000000
>
>
> What is the recommended way of grouping repetitive function calls?
> What do you usually use in your own documents? Regards
> Liviu

I would use the last method, or if the calls were truly repetitive (i.e. 
always identical, not just the same pattern), use a named chunk.

Duncan Murdoch



More information about the R-help mailing list