[R] avoiding a loop?

Marc Schwartz MSchwartz at mn.rr.com
Thu Oct 12 19:16:10 CEST 2006


On Thu, 2006-10-12 at 12:07 -0500, Marc Schwartz wrote:
> On Thu, 2006-10-12 at 12:43 -0400, Charles Annis, P.E. wrote:
> > I have a vector, (not a list)
> > > repeated.measures.FACTOR.names
> > [1] "Insp1" "Insp2" "Insp3" "Insp4" "Insp5" "Insp6" "Insp7" "Insp8" "Insp9"
> >  
> > and would like to convert this into a single string
> > "Insp1,Insp2,Insp3,Insp4,Insp5,Insp6,Insp7,Insp8,Insp9"
> > 
> > I can do that with a loop, but isn't there a more elegant way?
> > 
> > > result <- repeated.measures.FACTOR.names[[1]]
> > > for(i in 2:length(repeated.measures.FACTOR.names)) {
> > result <- paste(result, repeated.measures.FACTOR.names[[i]], sep=",") }
> > > result
> > [1] "Insp1,Insp2,Insp3,Insp4,Insp5,Insp6,Insp7,Insp8,Insp9"
> > > 
> 
> paste() is vectorized and note the use of 'collapse' in lieu of 'sep':
> 
> > paste(repeated.measures.FACTOR.names, collapse = ",")
> [1] "Insp1,Insp2,Insp3,Insp4,Insp5,Insp6,Insp7,Insp8,Insp9"


Before I forget, you can also do the following to reconstruct the
initial sequence and the final result in a single step:

> paste("Insp", 1:9, sep = "", collapse = ",")
[1] "Insp1,Insp2,Insp3,Insp4,Insp5,Insp6,Insp7,Insp8,Insp9"


In this case, we use 'sep' to indicate that there should be no space
between each occurrence of 'Insp' and the integers and then use
'collapse' to indicate (as above) that each alphanum construct is to be
joined by a comma into a single element.

HTH,

Marc



More information about the R-help mailing list