在excel (和Excel VBA)中,使用“&”连接文本和变量非常有用:
a = 5
msgbox "The value is: " & a将会给予
"The value is: 5"我如何在R中做到这一点?我知道有一种使用"paste“的方法。然而,我想知道是否有什么技巧可以像在Excel VBA中那样简单地完成。
提前谢谢。
发布于 2016-10-14 15:49:21
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"但是我还没有进行过广泛的测试,所以要注意意外的结果。
发布于 2016-10-31 06:10:33
另一种可能是使用sprintf
a <- 5
cat(sprintf("The value is %d\n",a))
## The value is 5%d表示整数格式(%f会给出"The value is 5.000000")。\n表示字符串末尾的换行符。
当你想把很多东西放在一起时,sprintf()可能比paste或paste0更方便。
sprintf("The value of a is %f (95% CI: {%f,%f})",
a_est,a_lwr,a_upr)https://stackoverflow.com/questions/40037608
复制相似问题