2013-01-16 33 views
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" 

我想要的东西,但是,该评论是在两个不同的行上返回的(它也可以是更多的行和不同的评论元素,任何想法都可以使用)

+0

'comment(sqrt_x)< - “我的评论”是一个更清晰的方式来指定评论。 –

+0

thx,但是,它不会给我更多的内线, – Toby

回答

3

由于Andrie说:你需要插入换行符。

如果您不想手动指定换行符的位置,则可以使用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 
) 
+0

好吧,我不想在我的控制台输入cat(comment(sqrt_x)),这有点尴尬。我希望源文件有一些快速的注释形式,以便其他人可以快速键入:注释(函数)并获得快速简单的帮助文本信息。不过,我希望它有一些结构。 – Toby

+0

编辑是伟大的,这是我真正要求。这是一个解决方法,但内部使用perfekt。 – Toby

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 
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()分手一个长字符串 分成部分)

如果你绝对绝望有这个你不喜欢多余的空格,你可能掩盖内置的东西,如@ RichieCotton的多版本comment功能:

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

但我这可能是个坏主意。