0

我正在寻找将字符串列表粘贴在一起以进入 SQL 语句的最佳方式...我在使用分隔栏时遇到问题 | 当我不希望它在开始时打印:

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"

我只想让它打印出“blah|blah|blah|blah”。我需要一个嵌套循环,还是 R 中有更好的迭代器来执行此操作?或者也许是输入 SQL 语句的更好方法?

4

3 回答 3

2

问题实际上是您第一次调用paste(paste_all_together,...)- 它实际上将空字符串粘贴到"blah",在它们之间放置 a |

这里已经有 2 个答案比我要建议的要好,但是用最少的手术来修复你的例子看起来像这样:

foo <- "blah"
all_together <- character(0)
for (n in 1:4) {
    all_together <- c(all_together, foo)
}
paste(all_together, collapse="|")
于 2010-03-18T21:18:26.553 回答
2

也许使用以下collapse选项:

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

产量

"bee|bar|baz"
于 2010-03-18T20:12:08.210 回答
1
paste(rep(foo,4),collapse='|')

[1] "blah|blah|blah|blah"
于 2010-03-18T20:25:00.050 回答