什么是相当于VB中的“&”在R?
在Excel(和Excel VBA)中,使用“&”连接文本和variables是非常有用的:
a = 5 msgbox "The value is: " & a
会给
"The value is: 5"
我怎样才能做到这一点在R? 我知道有一种方法可以使用“ 粘贴 ”。 但是,我不知道是否没有任何技巧像Excel VBA那样简单。
提前致谢。
这个博客文章build议定义你自己的连接运算符,它与VBA(和Javascript)有相似之处,但它保留了paste
:
"%+%" <- function(...) paste0(..., sep = "") "Concatenate hits " %+% "and this." # [1] "Concatenate hits and this."
我不是这个解决scheme的忠实粉丝,但是因为它掩盖了什么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,但是你应该考虑一下这个解决scheme对你来说是不是更令人困惑,而不是更有用。
如果你需要类似Javascript的解决scheme,你也可以试试这个:
"%+%" <- 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"
但我没有广泛的testing,所以要留意意想不到的结果。
另一种可能性是使用sprintf
:
a <- 5 cat(sprintf("The value is %d\n",a)) ## The value is 5
%d
表示整数格式( %f
会给“值是5.000000”)。 \n
表示string末尾的换行符。
sprintf()
可以比paste
或paste0
更方便,当你想把很多的东西放在一起时,例如
sprintf("The value of a is %f (95% CI: {%f,%f})", a_est,a_lwr,a_upr)