【问题标题】:How to get width of dataframe being printed in terminal in R如何获取在 R 终端中打印的数据框的宽度
【发布时间】:2015-06-29 18:01:48
【问题描述】:

我正在寻找一种方法来将底线放在我在 R 中打印出来的数据框下

输出看起来像

只要数据帧输出是,我想打印出底线。但是宽度不一样。

有什么想法吗?

编辑

我正在努力摆脱

cat("---------------------------------------\n")

并希望使给定数据帧的输出大小动态化。 “-----”行不应比数据框长或短。

【问题讨论】:

  • DataFrame[nrow(DataFrame),] 打印数据框的最后一行
  • 您正在尝试打印-------------
  • @Vlo 是的!它关于“32”和“平衡”之间的边界
  • 可以劫持默认的print.data.frame 例如:cake = print.data.frame;formals(cake)$g = substitute(20);body(cake)[[8]] = substitute(cat(paste0(rep("-", g), collapse="")));cake(iris, g = 64)
  • 但是,字符串的长度固定为 64。如何从给定的数据帧中获取宽度(例如字符数)?有没有办法让 g 值动态化?

标签: r terminal dataframe output


【解决方案1】:

使用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

【讨论】:

    【解决方案2】:

    看看它是如何工作的。非常简单的字符计数,没有花里胡哨,但应该可以完成预期的工作:

    编辑打印data.frame和函数中完成的行。

    # create a function that prints the data.frame with the line we want
    lineLength <- function( testDF )
    {
      # start with the characters in the row names, 
      #   plus empty space between columns
      dashes <- max( nchar( rownames( testDF ) ) ) + length ( testDF )
      # loop finding the longest string in each column, including header
      for( i in 1 : length ( testDF ) )
      {
        x <- nchar( colnames( testDF ) )[ i ]
        y <- max( nchar( testDF[ , i ] ) )
        if( x > y ) dashes <- dashes + x else dashes <- dashes + y
      }
      myLine <- paste( rep( "-", dashes ),  collapse = "" )
      print( testDF )
      cat( myLine, "\n" )
    }
    
    # sample data
    data( mtcars )
    
    # see how it works
    lineLength( head( mtcars ) )
                       mpg cyl disp  hp drat    wt  qsec vs am gear carb
    Mazda RX4         21.0   6  160 110 3.90 2.620 16.46  0  1    4    4
    Mazda RX4 Wag     21.0   6  160 110 3.90 2.875 17.02  0  1    4    4
    Datsun 710        22.8   4  108  93 3.85 2.320 18.61  1  1    4    1
    Hornet 4 Drive    21.4   6  258 110 3.08 3.215 19.44  1  0    3    1
    Hornet Sportabout 18.7   8  360 175 3.15 3.440 17.02  0  0    3    2
    Valiant           18.1   6  225 105 2.76 3.460 20.22  1  0    3    1
    -------------------------------------------------------------------- 
    

    【讨论】:

    • 不错!我更喜欢这个解决方案,因为我不必覆盖/添加新的打印功能。我可以轻松地将其嵌入到我的代码中。谢谢!
    猜你喜欢
    • 2015-07-31
    • 2017-10-23
    • 2010-11-04
    • 2011-01-05
    • 2012-01-21
    • 2012-09-30
    • 2018-04-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多