2

私が次の機能を持っているとしましょう:

sqrt_x = function(x) {
     sqrtx = x^0.5
     return(list("sqrtx" = sqrt))
}  
attr(sqrt_x, "comment") <- "This is a comment to be placed on two different lines"

私がタイプした場合

comment(sqrt_x) 

私は得る

[1] "This is a comment to be placed on two different lines"

しかし、私が欲しいのは、コメントが2つの異なる行で返されることです(それは、より多くの行と異なるコメント要素である可能性もあります。どんなアイデアでもありがたいです。

4

3 に答える 3

3

アンドリーが述べたように:改行文字を挿入する必要があります。

改行の行き先を手動で指定する必要がstrwrapない場合は、文字列が指定された幅を超えないように、便利なポイントでブレークを作成するために使用できます。

msg <- strwrap("This is a comment to be placed on two different lines", width = 20)
cat(msg, sep = "\n")
# This is a comment
# to be placed on two
# different lines

完全なソリューションは次のようになります。

#Add comment as normal
comment(sqrt_x) <- "This is a comment to be placed on two different lines"

#Display using this function
multiline_comment <- function(x, width = getOption("width") - 1L)
{
  cat(strwrap(comment(x), width = width), sep = "\n")
}

multiline_comment(
  sqrt_x, 
  20
)
于 2013-01-16T15:07:00.090 に答える
2

\n改行を挿入するために使用できます。このcatメソッドは、これを希望どおりに表示します。

attr(sqrt_x, "comment") <- "This is a comment to be placed on two\ndifferent lines"
cat(comment(sqrt_x))

This is a comment to be placed on two
different lines
于 2013-01-16T15:01:59.773 に答える
0

これはちょっとしたハックであり、おそらくあなたが望むものではありませんが、複数要素のcharacterベクトルを提供し、Rのデフォルトのフォーマットが複数の行にあるべきであると決定するのに十分な長さの行がある場合、あなたはあなたが望むものを得るかもしれません:

comment(sqrt_x) <- c("This is a comment                       ",
                     "to be placed on two different lines")
comment(sqrt_x)
## [1] "This is a comment                       "
## [2] "to be placed on two different lines"

format自動的にパディングするために使用できます:

comment(sqrt_x) <- format(c("This is a comment",
                            "to be placed on two different lines"),
                             width=50)

(他の場所に示されているようstrwrap()に、単一の長い文字列をパーツに分割するために使用することもできます)

これがどうしても必要で、余分なスペースが気に入らない場合は、comment@RichieCottonの複数行バージョンのようなもので組み込み関数をマスクできます。

comment <- function(x,width = getOption("width") - 1L) {
   cat(strwrap(base::comment(x), width = width), sep = "\n")
}

しかし、これはおそらく悪い考えです。

于 2013-01-16T16:35:19.843 に答える