将漂亮的data.frames / tables打印到控制台

时间:2015-09-03 11:44:00

标签: r printing console dataframe

有没有办法以更易读的方式将小data.frames打印到控制台?

例如,是否可以输出到控制台:

library(MASS)   
iris[1:5, ]

  Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1          5.1         3.5          1.4         0.2  setosa
2          4.9         3.0          1.4         0.2  setosa
3          4.7         3.2          1.3         0.2  setosa
4          4.6         3.1          1.5         0.2  setosa
5          5.0         3.6          1.4         0.2  setosa

作为

iris[1:5, ]

  +--------------+-------------+--------------+-------------+---------+
  | Sepal.Length | Sepal.Width | Petal.Length | Petal.Width | Species |
  +--------------+-------------+--------------+-------------+---------+
1 |          5.1 |         3.5 |          1.4 |         0.2 |  setosa |
2 |          4.9 |         3.0 |          1.4 |         0.2 |  setosa |
3 |          4.7 |         3.2 |          1.3 |         0.2 |  setosa |
4 |          4.6 |         3.1 |          1.5 |         0.2 |  setosa |
5 |          5.0 |         3.6 |          1.4 |         0.2 |  setosa |
  +--------------+-------------+--------------+-------------+---------+

我意识到对于大data.frames它会花费不必要的时间,但如果它是一个选项,我希望能够以更有条理的方式查看小帧。

特别是,当我有两个文本字段彼此相邻时,使用两个字段之间的管道将它们分开会更容易,因为字之间的间距与列之间的间距大小相同。

由于

4 个答案:

答案 0 :(得分:17)

如果它对任何人都有帮助,我只是偶然发现kable .Rprofile获得了漂亮的印刷品。结合上面的一些> knitr::kable(head(iris)) | Sepal.Length| Sepal.Width| Petal.Length| Petal.Width|Species | |------------:|-----------:|------------:|-----------:|:-------| | 5.1| 3.5| 1.4| 0.2|setosa | | 4.9| 3.0| 1.4| 0.2|setosa | | 4.7| 3.2| 1.3| 0.2|setosa | | 4.6| 3.1| 1.5| 0.2|setosa | | 5.0| 3.6| 1.4| 0.2|setosa | | 5.4| 3.9| 1.7| 0.4|setosa | 建议,这似乎实现了我的想法。

{{1}}

答案 1 :(得分:3)

您可以尝试几种方法。

  1. .Rprofile添加几个辅助函数。在我的个人资料中,我有

    hh = function(d) 
       if(class(d)=="matrix"|class(d)=="data.frame") d[1:5,1:5]
    

    此功能打印数据框的左上角。我也有

    ht = function(d, n=6) rbind(head(d, n), tail(d,n))
    
  2. 为数据框创建自己的S3打印功能,例如

    print.data.frame = function(x, ..., digits = NULL, 
                            quote = FALSE, right = TRUE, 
                            row.names = TRUE) 
                        message("hi")
    
  3. 使用套餐,例如dplyr。但是,如果你想要的只是漂亮的打印,那就有点矫枉过正了。

答案 2 :(得分:1)

在控制台中以颜色格式打印

tibble

library(tidyverse)

x <- as_tibble(mtcars)
x

enter image description here

答案 3 :(得分:0)

如果您也打开将输出打印到(RStudio)查看器窗格而不是控制台,我建议使用Require包。

DT

我认为这有几个优点:输出非常好且排列良好,包能够显示大型数据帧而不会变得麻烦,并且可以高度自定义启动。

enter image description here