在控制台输出中显示标签

Show labels in console output

我正在使用带标签的数据框。

library(dplyr)
library(sjmisc)
library(ggplot2)
data("diamonds")

df= tbl_df(diamonds) %>%
  select(cut, carat, price) %>%
  set_label(c("", "Kt", "EUR")) %>%
  slice(1:3)

在 R-Studio 中,数据框视图看起来应该是这样的:

df 打印到控制台时,dplyr 包将 tbl_df 对象重新格式化为:

Source: local data frame [3 x 3]

      cut carat price
   (fctr) (dbl) (int)
1   Ideal  0.23   326
2 Premium  0.21   326
3    Good  0.23   327

所以使用这个默认值标签会丢失(不是在数据框中,而是比较 R-Studio 视图和控制台)。

我正在寻找一个提供以下控制台输出的函数(根据标签交换 class 信息并可选择跳过源信息):

      cut carat price
       ()  (Kt) (EUR)
1   Ideal  0.23   326
2 Premium  0.21   326
3    Good  0.23   327

这是一个快速实现。我可以将它添加到我的 sjmisc 包中,如果它有用的话。

print.lbl_df <- function(x, n = NULL, width = NULL) {
  # get labels
  dlab <- sjmisc::get_label(x)
  # if x of class tbl_df?
  if (!"tbl_df" %in% class(x))
    x <- dplyr::tbl_df(x)
  # get df matrix
  dmat <- dplyr::trunc_mat(x, n = n, width = width)
  # set labels
  for (i in 1:ncol(dmat[[1]])) {
    # replace first value of each column, which is the class description
    # with variable label
    dmat[[1]][[i]][1] <- dlab[i]
  }
  # use dplyr-print method now
  print(dmat, n = n, width = width)
}

lbl_df <- function(x) {
  # add class attribute, if necessary
  if(!"lbl_df" %in% class(x))
    class(x) <- c("lbl_df", class(x))
  x
}

library(dplyr)
library(sjmisc)
library(ggplot2)
data("diamonds")

mydf <- lbl_df(tbl_df(diamonds) %>%
  select(cut, carat, price) %>%
  set_label(c("", "Kt", "EUR")) %>%
  slice(1:3))

mydf

>       cut carat price
>              Kt   EUR
> 1   Ideal  0.23   326
> 2 Premium  0.21   326
> 3    Good  0.23   327

编辑: 我已经在我的 sjmisc-package 中添加了一个 lbl_df 方法和一个通用的 print 方法,我将在今晚提交更改.如果你愿意,你可以安装最新版本 from GitHub.