views:

123

answers:

3

I'm blanking on the best way to paste a list of strings together to go into an SQL statement... I'm having trouble with the separator bar | printing at the beginning when I don't want it to:

foo = "blah"
paste_all_together = NULL
for (n in 1:4) {
    paste_together =     paste(foo ,sep = "")
    paste_all_together = paste(paste_all_together, paste_together, sep = "|")
    }

> paste_all_together
[1] "|blah|blah|blah|blah"

I just want it to print out "blah|blah|blah|blah". Do I need a nested loop, or is there a better itterator in R for doing this? Or perhaps a better way to input SQL statements?

+2  A: 

Perhaps use the collapse option:

foo = list('bee','bar','baz')
paste(foo,collapse='|')

yields

"bee|bar|baz"
unutbu
+1  A: 
paste(rep(foo,4),collapse='|')

[1] "blah|blah|blah|blah"
gd047
Thanks, but the strings were different, so ~unutbu's answer fits best
John
@John Your question and sample code suggests that strings are the same. Next time you could give all information in question.
Marek
yes you are right.
John
+2  A: 

The problem is actually the first time you call paste(paste_all_together,...) - it essentially pastes the empty string to "blah", putting a | between them.

There are already 2 answers here that are better than what I'm about to suggest, but to fix your example with minimal surgery would look something like this:

foo <- "blah"
all_together <- character(0)
for (n in 1:4) {
    all_together <- c(all_together, foo)
}
paste(all_together, collapse="|")
Ken Williams
ah great, that explains it!
John
actually, it gives the same result with or without the NULL, what made the difference is the placement of the paste function outside the for loop. Tks.
John
Thanks John - I actually realized that while I was posting but I forgot to change my first paragraph. =) Changing now.
Ken Williams