说我有以下功能:
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 :(得分: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
)
答案 1 :(得分: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
答案 2 :(得分: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")
}
但这可能是一个坏主意。