在Excel(和Excel VBA)这是真正有用的连接使用 “&” 的文字和变量:R中的VBAs“&”等价于什么?
a = 5
msgbox "The value is: " & a
会给
"The value is: 5"
如何在R中可以做到这一点?我知道有一种方法可以使用“paste”。不过,我想知道是否没有任何技巧能像Excel VBA那样简单。
在此先感谢。
在Excel(和Excel VBA)这是真正有用的连接使用 “&” 的文字和变量:R中的VBAs“&”等价于什么?
a = 5
msgbox "The value is: " & a
会给
"The value is: 5"
如何在R中可以做到这一点?我知道有一种方法可以使用“paste”。不过,我想知道是否没有任何技巧能像Excel VBA那样简单。
在此先感谢。
This blog post暗示来定义自己的连接符,这是类似于VBA(和JavaScript)的,但它保留的paste
功率:
"%+%" <- function(...) paste0(..., sep = "")
"Concatenate hits " %+% "and this."
# [1] "Concatenate hits and this."
我不是这个解决方案的大风扇,虽然因为它隐藏了什么paste
在引擎盖下。例如,你觉得这会发生吗?
"Concatenate this string " %+% "with this vector: " %+% 1:3
# [1] "Concatenate this string with this vector: 1"
# [2] "Concatenate this string with this vector: 2"
# [3] "Concatenate this string with this vector: 3"
在Javascript中的情况下,这将给你Concatenate this string with this vector: 1,2,3
,这是完全不同的。我不能说Excel,但你应该考虑这个解决方案对你来说不是更困难,而不是更有用。
如果你需要使用Javascript样的解决方案,你也可以试试这个:
"%+%" <- function(...) {
dots = list(...)
dots = rapply(dots, paste, collapse = ",")
paste(dots, collapse = "")
}
"Concatenate this string " %+% "with this string."
# [1] "Concatenate this string with this string."
"Concatenate this string " %+% "with this vector: " %+% 1:3
# [1] "Concatenate this string with this vector: 1,2,3"
但我还没有广泛的测试,所以要了望意想不到的效果。
另一种可能性是使用sprintf
:
a <- 5
cat(sprintf("The value is %d\n",a))
## The value is 5
的%d
表示整数格式化(%f
会给 “的值是5.000000”)。 \n
表示字符串末尾的换行符。
sprintf()
可以比paste
或paste0
更方便,当你想要放置很多件时,
sprintf("The value of a is %f (95% CI: {%f,%f})",
a_est,a_lwr,a_upr)
'paste'是非常简单的,以及'sprintf的( “值是:%d”,一)' –
遗憾,没有看到张贴的答案之前,您的评论... –