使用 cat() 和 paste() 在 R 控制台中连接和粘贴
Concatenating and Pasting within R console with cat() and paste()
我的问题可能有一个非常简单的解决方案,但我似乎没有找到它。
我有以下
p <- 0.95
我想在 R 控制台中显示结果。
我试过了
> cat("It is", p*100, "% accurate")
> cat("It is", p*100, paste("%", sep = ""), "accurate")
但我在数字和 %
之间得到一个 space
> cat("It is", p*100, "% accurate")
The classifier 95 % accurate
> cat("It is", p*100, paste("%", sep = ""), "accurate")
The classifier 95 % accurate
最终输出应该是
The classifier is 95% accurate
根据阅读文档不确定如何解决此问题
是sep
有什么帮助:
cat("It is ", p * 100, "% accurate", sep = "")
# It is 95% accurate
其中 sep
是
a character vector of strings to append after each element.
使用默认值 " "
,因此 space。这是最短的解决方案,而您也可以按照@Hanjo Jo'burg Odendaal 的建议使用 sprintf
或 paste
。
把计算移到里面就行了
cat("It is", paste0( p*100, "%"), "accurate")
paste0
是 shorthand 对于 sep = ""
。
胶水库也非常适合这个:
library(glue)
cat("It is", glue("{p*100}%"), "accurate")
我的问题可能有一个非常简单的解决方案,但我似乎没有找到它。
我有以下
p <- 0.95
我想在 R 控制台中显示结果。
我试过了
> cat("It is", p*100, "% accurate")
> cat("It is", p*100, paste("%", sep = ""), "accurate")
但我在数字和 %
之间得到一个 space> cat("It is", p*100, "% accurate")
The classifier 95 % accurate
> cat("It is", p*100, paste("%", sep = ""), "accurate")
The classifier 95 % accurate
最终输出应该是
The classifier is 95% accurate
根据阅读文档不确定如何解决此问题
是sep
有什么帮助:
cat("It is ", p * 100, "% accurate", sep = "")
# It is 95% accurate
其中 sep
是
a character vector of strings to append after each element.
使用默认值 " "
,因此 space。这是最短的解决方案,而您也可以按照@Hanjo Jo'burg Odendaal 的建议使用 sprintf
或 paste
。
把计算移到里面就行了
cat("It is", paste0( p*100, "%"), "accurate")
paste0
是 shorthand 对于 sep = ""
。
胶水库也非常适合这个:
library(glue)
cat("It is", glue("{p*100}%"), "accurate")