首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在R中,VBA "&“的等价物是什么?

在R中,VBA "&“的等价物是什么?
EN

Stack Overflow用户
提问于 2016-10-14 15:40:33
回答 2查看 264关注 0票数 3

在excel (和Excel VBA)中,使用“&”连接文本和变量非常有用:

代码语言:javascript
复制
a = 5
msgbox "The value is: " & a

将会给予

代码语言:javascript
复制
"The value is: 5"

我如何在R中做到这一点?我知道有一种使用"paste“的方法。然而,我想知道是否有什么技巧可以像在Excel VBA中那样简单地完成。

提前谢谢。

EN

回答 2

Stack Overflow用户

发布于 2016-10-14 15:49:21

This blog post建议定义您自己的连接运算符,这与VBA (和Javascript)类似,但它保留了paste的强大功能

代码语言:javascript
复制
"%+%" <- function(...) paste0(..., sep = "")

"Concatenate hits " %+% "and this."
# [1] "Concatenate hits and this."

不过,我并不是这个解决方案的粉丝,因为它有点掩盖了paste在幕后做什么。例如,你是否凭直觉认为会发生这种情况?

代码语言:javascript
复制
"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的解决方案,你也可以尝试这样做:

代码语言: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"

但是我还没有进行过广泛的测试,所以要注意意外的结果。

票数 5
EN

Stack Overflow用户

发布于 2016-10-31 06:10:33

另一种可能是使用sprintf

代码语言:javascript
复制
a <- 5
cat(sprintf("The value is %d\n",a))
## The value is 5

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

当你想把很多东西放在一起时,sprintf()可能比pastepaste0更方便。

代码语言:javascript
复制
sprintf("The value of a is %f (95% CI: {%f,%f})",
        a_est,a_lwr,a_upr)
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/40037608

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档