R:如何在循环中分离字符输出?

发布于 2024-08-25 07:04:56 字数 425 浏览 8 评论 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 语句的更好方法?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

中性美 2024-09-01 07:04:56

也许使用 collapse 选项:

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

yields

"bee|bar|baz"

Perhaps use the collapse option:

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

yields

"bee|bar|baz"
把人绕傻吧 2024-09-01 07:04:56

问题实际上是您第一次调用 paste(paste_all_together,...) 时 - 它实际上将空字符串粘贴到 "blah" 中,并放置 |< /code> 他们之间。

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

foo <- "blah"
all_together <- character(0)
for (n in 1:4) {
    all_together <- c(all_together, foo)
}
paste(all_together, collapse="|")

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="|")
风流物 2024-09-01 07:04:56
paste(rep(foo,4),collapse='|')

[1] "blah|blah|blah|blah"
paste(rep(foo,4),collapse='|')

[1] "blah|blah|blah|blah"
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文