开发者

R: How to separate character output in a loop?

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 doi开发者_JS百科ng this? Or perhaps a better way to input SQL statements?


Perhaps use the collapse option:

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

yields

"bee|bar|baz"


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="|")


paste(rep(foo,4),collapse='|')

[1] "blah|blah|blah|blah"
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜