# Sweave: How to remove horizontal space in Soutput environments?

As the following example shows, there is a horizontal space added in the Soutput environment. This leads to a non-left-aligned output (see the output of rnorm(). I found that this space already exists in "standard R output" (in interactive mode), the question is if it can be avoided somehow?

\documentclass{article}

\usepackage[american]{babel}
\usepackage{fancyvrb}
\usepackage{Sweave}

\begin{document}
\noindent Just some text before the chunk
<<foo>>=
set.seed(1)
rnorm(10)
3 != 4
@
Just some text after the chunk
\end{document}

-

This is probably not a really LaTeX question -- as you mentioned, the space exists in R output, and it is not caused by the Soutput environment.

The reason that the space was added in the output is that you were printing 10 numbers, and R has to reserve one space to make sure the alignment of all lines works well, e.g. the output may have a potential index [10] in the last line, which has two characters, while previous indices only has one character, e.g. [1], [2], ...

Note how the number of spaces increases as the number of elements in the vector increases:

> options(width = 30)
> 1  # no space
[1] 1
> 1:10
[1]  1  2  3  4  5  6  7  8
[9]  9 10
> 1:20
[1]  1  2  3  4  5  6  7  8
[9]  9 10 11 12 13 14 15 16
[17] 17 18 19 20
> 1:100  # two spaces now
[1]   1   2   3   4   5   6
[7]   7   8   9  10  11  12
[13]  13  14  15  16  17  18
[19]  19  20  21  22  23  24
....


There is one solution if you use the knitr package instead of Sweave, though. The basic idea is to remove the extra space from the beginning of the lines using an output hook function.

\documentclass{article}

<<setup, include=FALSE>>=
# modify the default hook to remove spaces before writing output
hook_output = knit_hooks$get('output') knit_hooks$set(output = function(x, options) {
s = options\$rm.spaces
if (!is.null(s)) x = gsub(sprintf('(^|\n)%s', s), '\\1', x)
hook_output(x, options)
})
@

\begin{document}
\noindent Just some text before the chunk
<<foo, comment=NA, rm.spaces=' '>>=
set.seed(1)
rnorm(10)
3 != 4
@
Just some text after the chunk
\end{document}


To compile the document, use library(knitr); knit('yourfile.Rnw') instead of Sweave('yourfile.Rnw').

-