string 连接字符串中的数值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13268698/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 01:41:40  来源:igfitidea点击:

Concatenate numerical values in a string

stringrconcatenationpastecat

提问by kahlo

I would like to store this output in a string:

我想将此输出存储在一个字符串中:

> x=1:5
> cat("hi",x)
hi 1 2 3 4 5

So I use paste, but I obtain this different result:

所以我使用paste,但我得到了不同的结果:

> paste("hi",x)
[1] "hi 1" "hi 2" "hi 3" "hi 4" "hi 5"

Any idea how to obtain the string:

任何想法如何获取字符串:

"hi 1 2 3 4 5"

Thank you very much!

非常感谢!

回答by Gavin Simpson

You can force coercion to character for xby concatenating the string "hi"on to x. Then just use paste()with the collapseargument. As in

您可以强制胁迫字符x通过连接字符串"hi"x。然后只需paste()collapse参数一起使用。如

x <- 1:5
paste(c("hi", x), collapse = " ")

> paste(c("hi", x), collapse = " ")
[1] "hi 1 2 3 4 5"

回答by mnel

You could use capture.outputwith cat

你可以capture.output和 cat 一起使用

capture.output(cat('hi',x))
[1] "hi 1 2 3 4 5"

回答by loretoparisi

You use sprintf:

你使用sprintf

> x=1:5
> str=sprintf("hi %d",x)
> str
[1] "hi 1" "hi 2" "hi 3" "hi 4" "hi 5"
>