在R中,“&”的等价物是什么?

3
在Excel(和Excel VBA)中,使用“&”连接文本和变量非常有帮助:
a = 5
msgbox "The value is: " & a

将会给予

"The value is: 5"

我该如何在R中实现这个功能?我知道可以使用 "paste"。但我想知道是否有类似Excel VBA那样简单的方法。
提前感谢。

3
“paste”相当简单,以及sprintf("The value is: %d", a) - Rich Scriven
抱歉,在发布答案之前没有看到您的评论... - Ben Bolker
2个回答

5

这篇博客文章建议定义自己的连接运算符,类似于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中,这将给你将此字符串与此向量连接: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"

但我没有进行广泛的测试,因此请留意可能出现的意外结果。


1
另一种可能性是使用 sprintf
a <- 5
cat(sprintf("The value is %d\n",a))
## The value is 5

%d 表示整数格式化(%f 将会给出 "The value is 5.000000" )。\n 在字符串末尾表示换行。

当你想要组合很多片段时,sprintf()pastepaste0 更方便。

sprintf("The value of a is %f (95% CI: {%f,%f})",
        a_est,a_lwr,a_upr)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接