使用getOption("width"):
> getOption("width")
[1] 80
您可以通过?options查看此选项的说明
‘width’: controls the maximum number of columns on a line used in
printing vectors, matrices and arrays, and when filling by
‘cat’.
这并不意味着使用了整个 80 个(在我的情况下)字符,但 R 的打印不应超出此范围,因此它应该是 上限。
您可能还应该在 IDE 或其他 R 前端中检查这一点。例如,RStudio 可能会根据其应用程序中控制台小部件的宽度执行不同的操作。
要真正准确地格式化数据框的正确宽度,您需要将数据框处理为每行的字符串(就像print.data.frame 通过其format 方法所做的那样。类似于:
df <- data.frame(Price = round(runif(10), 2),
Date = Sys.Date() + 0:9,
Subject = rep(c("Foo", "Bar", "DJGHSJIBIBFUIBSFIUBFUIS"),
length.out = 10),
Category = rep("Media", 10))
class(df) <- c("MyDF", "data.frame")
print.MyDF <- function(x, ...) {
fdf <- format(x)
strings <- apply(x, 2, function(x) unlist(format(x)))[1, ]
rowname <- format(rownames(fdf))[[1]]
strings <- c(rowname, strings)
widths <- nchar(strings)
names <- c("", colnames(x))
widths <- pmax(nchar(strings), nchar(names))
csum <- sum(widths + 1) - 1
print.data.frame(df)
writeLines(paste(rep("-", csum), collapse = ""))
writeLines("Balance: 48") ## FIXME !!
invisible(x)
}
给出:
> df
Price Date Subject Category
1 0.73 2015-06-29 Foo Media
2 0.11 2015-06-30 Bar Media
3 0.19 2015-07-01 DJGHSJIBIBFUIBSFIUBFUIS Media
4 0.54 2015-07-02 Foo Media
5 0.04 2015-07-03 Bar Media
6 0.37 2015-07-04 DJGHSJIBIBFUIBSFIUBFUIS Media
7 0.59 2015-07-05 Foo Media
8 0.85 2015-07-06 Bar Media
9 0.15 2015-07-07 DJGHSJIBIBFUIBSFIUBFUIS Media
10 0.05 2015-07-08 Foo Media
----------------------------------------------------
Balance: 48