2016-10-14 7 views
3

"&" を使用して、テキストと変数を接続するために本当に便利です:RのVBA "&"と同等のものは何ですか?エクセル(エクセルVBA)で

a = 5 
msgbox "The value is: " & a 

は、私はRでこれを行うことができますどのように

"The value is: 5" 

を与えるのだろうか?私は "paste"を使用する方法があることを知っています。しかし、Excel VBAのようにシンプルな操作をするためのトリックがないのだろうかと思います。

ありがとうございます。

+3

'paste'は非常に単純であるだけでなく、'はsprintfは( "値は次のとおりです。%D"、a)は ' –

+0

申し訳ありませんが、答えを投稿する前にあなたのコメントを見ていません... –

答えて

5

This blog postは、どのようなVBA(とJavascript)に似ている、独自の連結演算子を定義することを提案があるが、それはpasteの力を保持:

"%+%" <- 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" 

、これはかなり異なっている、あなたに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" 

しかし、私は徹底的にテストしていないので、予期しない結果のために目を光らせて。

1

別の可能性は、sprintfを使用することである。

a <- 5 
cat(sprintf("The value is %d\n",a)) 
## The value is 5 

%dは書式の整数を表し、(%f "は値が5.000000である" 与えます)。 \nは、文字列の最後の改行を示します。

sprintf()など多くの部分をまとめたい場合は、pasteまたはpaste0よりも便利です。

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