Re: [R] How to merge two strings

From: Prof Brian Ripley <ripley_at_stats.ox.ac.uk>
Date: Tue 16 Aug 2005 - 23:15:00 EST

On Tue, 16 Aug 2005, Barry Rowlingson wrote:

> Claus Hindsgaul wrote:
>> Thank you all!
>> Paste() was just the function I needed to know!
>
> Or sprintf:
>
> > s1 <- "R-"
> > s2 <- "project"
> > sprintf("%s%s",s1,s2)
> [1] "R-project"
>
> It seems to be much faster:
>
> > unix.time(for(i in 1:100000){junk=sprintf("%s%s",s1,s2)})
> [1] 1.12 0.00 1.12 0.00 0.00
> > unix.time(for(i in 1:100000){junk=paste(s1,s2,sep='')})
> [1] 5.90 0.01 5.92 0.00 0.00
>
> Not that I imagine string concatenation will ever be a bottleneck
> worth optimising but there it is. A well-constructed sprintf() call may
> be more readable than a pastey mess though, with all its fiddly commas
> and quotes - contrived example:
>
> > sprintf("%s://%s%s/%s",scheme,host,dir,file)
> [1] "http://www.foo.com/foo/bar/baz.txt"
>
> > paste(scheme,'://',host,dir,'/',file,sep='')
> [1] "http://www.foo.com/foo/bar/baz.txt"
>
> which do you prefer?

That's actually the reason we have the enhanced sprintf that we do nowadays: to enable readable (and translatable) error messages to be written via gettextf.

-- 
Brian D. Ripley,                  ripley@stats.ox.ac.uk
Professor of Applied Statistics,  http://www.stats.ox.ac.uk/~ripley/
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272866 (PA)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595

______________________________________________
R-help@stat.math.ethz.ch mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html
Received on Tue Aug 16 23:19:24 2005

This archive was generated by hypermail 2.1.8 : Sun 23 Oct 2005 - 15:23:32 EST