[R] vector sprintf argument

Christos Hatzis christos at nuverabio.com
Fri Nov 30 06:08:03 CET 2007


According to the help page sprintf will recycle its arguments:

The arguments (including fmt) are recycled if possible a whole number of
times to the length of the longest, and then the formatting is done in
parallel.  

Therefore the following works:

> sprintf("Number: %d", A)
[1] "Number: 3" "Number: 4" "Number: 5"

Another option is to create a character string from A and then print it:

> sprintf("Number: %s", paste(A, collapse=" "))
[1] "Number: 3 4 5"

-Christos

> -----Original Message-----
> From: r-help-bounces at r-project.org 
> [mailto:r-help-bounces at r-project.org] On Behalf Of Moshe Olshansky
> Sent: Thursday, November 29, 2007 11:45 PM
> To: Tom Sgouros; r-help at r-project.org
> Subject: Re: [R] vector sprintf argument
> 
> The only thing I can think of is:
> 
> > a <- c(1,2.7,5.19)
> > F<-c("numeric:  %d ","%g ","%8.3f")
> > x<-sapply(1:length(a),function(i)
> sprintf(F[i],a[i]))
> > y<-paste(x,sep="",collapse="")
> 
> But I am sure that you will get a better advice elsewhere.
> 
> --- Tom Sgouros <tomfool at as220.org> wrote:
> 
> > 
> > Hello all:
> > 
> > If I have a vector and a format, I want to do this:
> > 
> >  > A <- c(3,4,5)
> >  > F <- "Number: %d, %d, %d"
> >  > sprintf(F,A)
> > 
> > This doesn't work because A isn't three arguments, it's 
> just one.  Is 
> > there a way to peel the vector members out of A so that sprintf can 
> > get at them?
> > 
> > I would like to do this because I have a large set of 
> variable-length 
> > data that I'd like to print out in fancy formatted form.  
> The vectors 
> > range in length from 2 to 7.  Each row is different, so I had been 
> > hoping to do this with an array of formats, too.
> > 
> > I feel like I'm either overlooking something obvious, or have 
> > determined to do this in an un-R fashion.  Any advice is 
> welcome.  (On 
> > this topic, that is.)
> > 
> > Many thanks,
> > 
> >  -tom
> > 
> > 
> > --
> >  ------------------------
> >  tomfool at as220 dot org
> >  http://sgouros.com
> >  http://whatcheer.net
> > 
> > ______________________________________________
> > 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