[R] break the long R code lines automatically

Charles C. Berry cberry at tajo.ucsd.edu
Tue Aug 24 23:07:27 CEST 2010


On Tue, 24 Aug 2010, heyi xiao wrote:

>
>
>
>
> Dear
> all,
>
> I have
> written some R source program with many thousands of lines. I didn’t insert
> line breaks automatically or manually for the long lines. But now I would like
> to edit the source code in Emacs/ESS to make it more formal as a package. One of
> the major problems here is how to break the long lines automatically. Emacs auto-fill-mode
> only works for the lines you are typing in currently, and fill commands like M-q
> (fill-paragraph) or M-x fill-region (fill-region) mess up the R code lines as
> they take a whole function/paragraph as a long line, and remove the original
> line breaks.
>
> I find
> simple solutions for indenting code regions in Emacs/ESS, but no good ones for
> breaking code lines. However, I saw the nice multi-line codes in all
> R/Bioconductor packages. Please let me know if you have any ideas on how people
> usually break the existent long R code lines automatically. I will really
> appreciate your kind help!


Not particualrly elegant, but a combination of parse and print will break 
long lines:


> cat("y <- ",paste( 1:20,collapse=" + "),"\n","y2 <- ",
+  paste( 1:20,collapse="+"),"\n",file="testwrap.R")
> for (iexpr in parse("testwrap.R")) print(iexpr)
y <- 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 + 11 + 12 + 13 +
     14 + 15 + 16 + 17 + 18 + 19 + 20
y2 <- 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 + 11 + 12 + 13 +
     14 + 15 + 16 + 17 + 18 + 19 + 20
>
> nchar(readLines("testwrap.R"))
[1] 95 59
>

and of course you will want 'sink' or some such to save the lines.

HTH,

Chuck


>
> Heyi
>
>
>
>
>
> 	[[alternative HTML version deleted]]
>
>

Charles C. Berry                            (858) 534-2098
                                             Dept of Family/Preventive Medicine
E mailto:cberry at tajo.ucsd.edu	            UC San Diego
http://famprevmed.ucsd.edu/faculty/cberry/  La Jolla, San Diego 92093-0901



More information about the R-help mailing list