这篇博客文章建议定义自己的连接运算符,类似于VBA(和Javascript),但保留了paste
的强大功能:
"%+%" <- function(...) paste0(..., sep = "")
"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."
"Concatenate this string " %+% "with this vector: " %+% 1:3
但我没有进行广泛的测试,因此请留意可能出现的意外结果。
sprintf("The value is: %d", a)
。 - Rich Scriven