[R] Replacing tabs with appropriate number of spaces

Gabor Grothendieck ggrothendieck at gmail.com
Tue Dec 9 19:45:21 CET 2008


That's a clever use of gsubfn.  Here is a very minor simplification using
the same code but representing it in formula notation and sprintf:

gsubfn('([^\t]+)\t', ~ sprintf("%s%*s", x, 8-nchar(x)%%8, " "), tmp)


On Tue, Dec 9, 2008 at 12:51 PM, Greg Snow <Greg.Snow at imail.org> wrote:
> This is basically your approach, but automated a bit more than you describe:
>
>
> library(gsubfn)
>
> tmp <- strsplit('one\ttwo\nthree\tfour\n12345678\t910\na\tbc\tdef\tghi\n','\n')[[1]]
>
> tmp2 <- gsubfn('([^\t]+)\t', function(x) {
>  ln <- nchar(x)
>  nsp <- 8-(ln %% 8)
>  sp <- paste( rep(' ', nsp), collapse='' )
>  paste(x,sp, sep='')
> }, tmp )
>
> tmp2
> cat(tmp2, sep='\n')
>
> This is based on the assumption of tab stops every 8 columns, change the 2 8's above if you want something different.
>
> Hope this helps,
>
>
> --
> Gregory (Greg) L. Snow Ph.D.
> Statistical Data Center
> Intermountain Healthcare
> greg.snow at imail.org
> 801.408.8111
>
>
>> -----Original Message-----
>> From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-
>> project.org] On Behalf Of Dennis Fisher
>> Sent: Tuesday, December 09, 2008 9:40 AM
>> To: r-help at stat.math.ethz.ch
>> Subject: [R] Replacing tabs with appropriate number of spaces
>>
>> Colleagues,
>>
>> Platform: OS X (but issue applies to all platforms)
>> Version: 2.8.0
>>
>> I have a mixture of text and data that I am outputting via R to a pdf
>> document (using a fixed-width font).  The text contains tabs that
>> align columns properly with a fixed-width font in a terminal window.
>> However, when the PDF document is created, the concept of a tab is not
>> invoked properly and columns do not align.
>>
>> I could use brute force as follows:
>> 1.  identify lines of text containing tabs
>> 2.  strsplit on tabs
>> 3.  count characters preceding the tab, then replace the tab with the
>> appropriate number of spaces (e.g., if the string preceding the tab
>> has 29 characters, add 3 spaces), then paste(..., sep="")
>>
>> However, I am sure a more elegant approach exists.  Can anyone offer
>> one?
>>
>> Dennis
>>
>>
>> Dennis Fisher MD
>> P < (The "P Less Than" Company)
>> Phone: 1-866-PLessThan (1-866-753-7784)
>> Fax: 1-415-564-2220
>> www.PLessThan.com
>>
>> ______________________________________________
>> 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.
>
> ______________________________________________
> 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