R Jupyter Notebook 在函数内的漂亮打印

问题描述

在 jupyter notebook 的单元格中调用 head(...) 时,我们得到了一个包含数据的漂亮表格

enter image description here

但是,如果我想在函数中执行相同操作,则不会显示任何内容,因此我必须使用 print(head(...)),但结果不如您所见

enter image description here

有没有办法在函数中获得与第一张图像相同类型的输出

解决方法

用于 IRkernel 的 Jupyter 显示功能由 IRdisplay 包提供,该包与 IRkernel 一起安装(默认情况下)。只需使用:

IRdisplay::display(CO2)

或者先将库加载到命名空间中:

library(IRdisplay)
data("CO2")
a <- function() {
    display(head(CO2))
}
a()

按预期工作:

enter image description here