GithubHelp home page GithubHelp logo

printr's Introduction

printr

R-CMD-check

This is a companion package to knitr. Its main purpose is to extend the S3 generic function knit_print() in knitr, which is the default value of the chunk option render, as explained in the vignette knit_print.html.

You can install the stable version from CRAN or the development version from my personal repo:

# CRAN version
install.packages('printr')

# or the dev version
install.packages(
  'printr',
  repos = c('https://yihui.r-universe.dev', 'https://cran.rstudio.com')
)

To enable the printing methods defined in this package, just library(printr) in a code chunk (in the beginning) of your knitr document. Then some objects will be printed differently with what you would have seen in a normal R console. For example:

  • matrices, data frames, and contingency tables are printed as tables (LaTeX, HTML, or Markdown, depending on your output format)
  • the help page (from ?foo or help(foo)) can be rendered as HTML, LaTeX, or plain text, and you can also specify which section(s) of the help page to include in the output
  • the results from browseVignettes(), help.search(), data(), and vignette() are rendered as tables
  • the package information from library(help = 'foo') is rendered as plain text

For more information, please check out the package vignette:

vignette('printr', package = 'printr')

You are welcome to contribute more S3 methods to this package, and you may want to read the existing methods in this package before you get started. In most cases, I guess you will end up rendering either plain text (see knit_print.packageInfo for example) or tables (see knit_print.matrix) in the output.

printr's People

Contributors

cderv avatar yihui avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

printr's Issues

Response.name for high-dimensional tables

Thanks for the useful package. I'm printing a 3-dimensional table as the result of prop.table() call. In the code, as.data.table() is called for high-dimensional tables, which uses response.name= "Freq" by default. "Freq" response name is misleading in my case, but I don't think there is a way to change it.

Support for matrices

I can't seem to get matrices to print with this package. Everything works fine for dataframes, ?foo, etc, but not matrices. The screenshot summarizes the situation.

printr

support for multiway table?

printr gives beautiful output for table(). Is there any plan for supporting multi-way table generated by ftable()?

An RMD example:


---
title: "Untitled"
author: ""
date: ""
output: pdf_document

---


```{r, echo=FALSE}
library(knitr)
library(printr)
table(mtcars[c("cyl", "vs", "am", "gear")])
ftable(mtcars[c("cyl", "vs", "am", "gear")],
       row.vars = 1:3)
```  ```

knit_print is not the default currently

This is just a minor note, but render currently defaults to NULL, not to knit_print as you say here and in the vignette. You do a bit of black magic for htmlwidgets, before passing things along to knit_print. Or maybe it's not black magic, but it tripped me up when I tried to handle things with pander where possible.

vignette not included

I know where to find the vignette, but it is not included in the distribution (0.0.6). So the mentioned

vignette('printr', package = 'printr')

does not work

Use repr instead

Instead of reproducing everything repr has been doing for a long time, knit_print should use repr instead of this.

Offer a way to use paged_table() feature from R Markdown within Quarto

See this discussion: quarto-dev/quarto-cli#933 (reply in thread)

df_print is not a Quarto feature. But while writing an example on how it would work, I am wondering if we should not adapa printr package to allow opt-in some mechanism for chunk.

Currently printr only modifies by default the method knit_print but we could offer other mechanism.

For example this is an example of creating a df_print chunk option

```{r}
kable_print <- function(x, options) {
  knitr::asis_output(
    paste(c("", "", knitr::kable(x)), collapse = "\n")
  )
}

paged_print <- function(x, options) {
  knitr::asis_output(
    rmarkdown:::paged_table_html(x, options = attr(
      x,
      "options"
    )),
    meta = list(dependencies = rmarkdown::html_dependency_pagedtable())
  )
}

knitr::opts_hooks$set(df_print = function(options) {
  if (options$df_print == "paged") {
    options$render = paged_print
  } else if (options$df_print == "kable") {
    options$render = kable_print
  }
  options
})

```

```{r, df_print = "paged"}
iris
```

```{r, df_print = "kable"}
head(iris)
```

```{r}
head(iris)
```

This works well within Quarto. As other option described in quarto-dev/quarto-cli#933 (reply in thread)

This is to share some thoughts and idea. I think there is some useful change we could do.

Anyway, main addition in printr would be a knit_print method for paged_df maybe.

Make functionality modular

Thanks for this nice package. I am a teacher mainly interested in including sections of help pages in my xaringan presentations so that I can explain functions to students. However, I still want my tibbles printed in the regular way. Could you make the functionality modular so that we can choose what gets pretty-printed?

error installing printr on R 3.3.0

Hi, after upgrading from R 3.2 to 3.3.0 I am no longer able to install your readr.
Is there any workaround this?

install.packages('printr')
Installing package into ‘C:/Users/lucas_000/Documents/R/win-library/3.3’
(as ‘lib’ is unspecified)
Warning in install.packages :
  package ‘printr’ is not available (for R version 3.3.0)

> sessionInfo()
R version 3.3.0 (2016-05-03)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows >= 8 x64 (build 9200)

locale:
[1] LC_COLLATE=Portuguese_Brazil.1252  LC_CTYPE=Portuguese_Brazil.1252   
[3] LC_MONETARY=Portuguese_Brazil.1252 LC_NUMERIC=C                      
[5] LC_TIME=Portuguese_Brazil.1252    

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

loaded via a namespace (and not attached):
[1] tools_3.3.0

compatibility with microbenchmark

I cannot make printr and microbenchmark work well together. For example:


---
title: "test"
author: "Ignacio"
output: html_document

---

```{r}
library(printr)
library(microbenchmark)
a1 <- a2 <- a3 <- a4 <- numeric(0)

res <- microbenchmark(a1 <- c(a1, 1),
                      a2 <- append(a2, 1),
                      a3[length(a3) + 1] <- 1,
                      a4[[length(a4) + 1]] <- 1,
                      times=100L)
tbl<-print(res)
tbl
```

Prints the table twice, once with good formatting and one without. If i change

tbl<-print(res)
tbl

to just

print(res)

I get the table without formatting.

Thanks!

named index of data.frame

---
title: "Untitled"
author: "Andrew Tang"
date: "2016/10/4"
output: html_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(printr)
```

```{r}
iris['Sepal.Length']
```

In the knit HTML result, Sepal.Length will be a title.

format 1-dim table in multiple lines

How to fit the table output according to the page width when using printr table function?

table(sample(stringi::stri_rand_strings(20, 3), 200, replace = TRUE))

2

The output of the above code exceeds the page width. How to print the table into multiple lines if the width is exceeding the page width?

  • setting the width options(width = 10) did not help either.

Limit table size in latex

I would like an option to limit the maximum rows/cols for latex output. An option similar to options(dplyr.print_max = 10) would be good. There should be some indication of how many rows & columns are omitted, similar to the tibble string output.

I have a few tables with hundreds of rows and columns. In the notebook preview these print nicely as tibble truncated tables (10 rows max), but when rendered to PDF I get pages of tables which also overflow the right margin.

Markdown violation

As I mentioned in another Issue, I don't like the TOC at the very vignette beginning.

To circumvent that, I am customizing the style sheet and using the following markup pattern where I want the TOC:

<div id="TOC">
<div class="toctitle">Table of Contents </div>
- [Digesting the Image Samples](#digest)
- [Getting the Computed Values](#result)
  * [Variance Result](#var)
  * [Covariance Result](#cov)
- [Introduction to Model Fitting](#intro-fit)  
</div>

However , the inner list (with the "Variance.." and "Covariance..." items), is ignored in the final html. They appear at the same level as the other LI items and not inside their own UL tag list.

I have to add "manual" UL tags to circumvent his:

<div id="TOC">
<div class="toctitle">Table of Contents </div>
- [Digesting the Image Samples](#digest)
- [Getting the Computed Values](#result)
<ul>
  * [Variance Result](#var)
  * [Covariance Result](#cov)
</ul>
- [Introduction to Model Fitting](#intro-fit)  
</div>

Thanks in advance.

kable() and the margin of the page

Hy all!

I want to control the way the table is printed using the kable function().

Instead of printing like this: (Because I don't like the extra space between columns)
capture2

I would like to print like this:
capture

I saw that depending on the template, the output of kable is different. How can I control it?

Thanks in advance,
Guilherme

1-dim table with caption

I have seen #15 how to print a caption with table, but I did not find a solution how to add a caption to a simple 1-dim table when printr is loaded.

This gives a subscript error

x1 = sample(letters[1:3], 1000, TRUE)
kable(table(x1), caption = "...")
table(x1)  # nice printout with knitr, but no caption

print.summary.lm method

Hi,

A print.summary.lm method would be amazing.

I am using summary(x)$coef right now, which also works nicely, just as with kable but much cleaner!

However, eventually there might be value in creating a specific method method such that you could simple enter:

<<model1>>=
summary(lm(y ~ X, data=df))
@

Which would then print a formatted table.

Thanks!

Positioning the TOC

It would be great if it were possible to select were the TOC will appear.

I like to show the TOC after a brief introduction, the same style used by wikipedia. That way, the items in the TOC makes more sense to the primer.

This post is about an enhancement, but I don't know how to classify it that way.

prints complete table with data.table when update by reference


---
title: "copy this into a Rmd"
author: "Henk Harmsen"
date: "September 10, 2015"
output: html_document

---

```{r}
library(data.table)

data(mtcars)
df = data.table(mtcars)
```

this works, no intention to print/head table:

```{r}
df[, mpg2 := mpg * 2]
```

but after loading printr, update by reference prints out the whole table:

```{r}
library(printr)
df[, mpg3 := mpg2 / 2]
```

printr doesn't work when used outside RStudio

If I run this from the terminal

curl https://raw.githubusercontent.com/yihui/printr/master/vignettes/printr.Rmd > /tmp/printr.Rmd; Rscript -e 'library(knitr); library(printr); knit2html("/tmp/printr.Rmd")'

the file produced doesn't have the pretty tables

screenshot from 2015-03-17 18 35 11

However, I knit the vignette in RStudio it works fine.

Grouped tibble (`grouped_df`) is not handled by printr

Tibbles do not render correctly all the time when printr is used. If they are grouped, they are rendered as plain text.

Versions:

  • printr 0.1
  • knitr 1.20

Below is a reproducible example:

library(dplyr)
library(printr)

Normal tibble is rendered as table

mtcars %>% head
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

Grouped tibble is rendered as text

mtcars %>% group_by(cyl)  %>% head
## # A tibble: 6 x 11
## # Groups:   cyl [3]
##     mpg   cyl  disp    hp  drat    wt  qsec    vs    am  gear  carb
##   <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
## 1  21.0    6.  160.  110.  3.90  2.62  16.5    0.    1.    4.    4.
## 2  21.0    6.  160.  110.  3.90  2.88  17.0    0.    1.    4.    4.
## 3  22.8    4.  108.   93.  3.85  2.32  18.6    1.    1.    4.    1.
## 4  21.4    6.  258.  110.  3.08  3.22  19.4    1.    0.    3.    1.
## 5  18.7    8.  360.  175.  3.15  3.44  17.0    0.    0.    3.    2.
## 6  18.1    6.  225.  105.  2.76  3.46  20.2    1.    0.    3.    1.

Removing the class "grouped_df" leads to correct rendering again

class(x) <- setdiff(class(x),"grouped_df")
x %>% head
mpg cyl disp hp drat wt qsec vs am gear carb
21.0 6 160 110 3.90 2.620 16.46 0 1 4 4
21.0 6 160 110 3.90 2.875 17.02 0 1 4 4
22.8 4 108 93 3.85 2.320 18.61 1 1 4 1
21.4 6 258 110 3.08 3.215 19.44 1 0 3 1
18.7 8 360 175 3.15 3.440 17.02 0 0 3 2
18.1 6 225 105 2.76 3.460 20.22 1 0 3 1

printr labels + kable caption

I cannot get both printr and kable's caption option working together. This might be a bug or I am missing something simple. An example, not sure how to format it to be more readable, so a .txt and .pdf with printed .html attached:
printr_test.pdf
printr_test.txt

r global options, packages etc. (as text)

{r global_options, include = FALSE}
knitr::opts_chunk$set(fig.width = 6, fig.height = 4, fig.path = 'Figs/',
echo = TRUE, warning = FALSE, message = FALSE,
cache = TRUE, tidy = FALSE, size = "small")
options(width = 10000)

{r load packages, cache = FALSE}
library(printr)
library(knitr)

{r session, cache = FALSE}
sessionInfo()

## R version 3.2.4 Revised (2016-03-16 r70336)
## Platform: x86_64-w64-mingw32/x64 (64-bit)
## Running under: Windows 7 x64 (build 7601) Service Pack 1
## 
## locale:
## [1] LC_COLLATE=English_United Kingdom.1252  LC_CTYPE=English_United Kingdom.1252    LC_MONETARY=English_United Kingdom.1252 LC_NUMERIC=C                            LC_TIME=English_United Kingdom.1252    
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
## [1] knitr_1.12.3 printr_0.0.5
## 
## loaded via a namespace (and not attached):
##  [1] magrittr_1.5    formatR_1.3     tools_3.2.4     htmltools_0.3.5 yaml_2.1.13     Rcpp_0.12.4     stringi_1.0-1   rmarkdown_0.9.5 stringr_1.0.0   digest_0.6.9    evaluate_0.8.3
printr (labels)
set.seed(2016)
x1 = sample(letters[1:3], 1000, TRUE)
x2 = sample(letters[1:3], 1000, TRUE)
t <- table(x1, x2, dnn = c("Sample A", "Sample B"))
t
printr + kable (caption, NO labels...)
set.seed(2016)
x1 = sample(letters[1:3], 1000, TRUE)
x2 = sample(letters[1:3], 1000, TRUE)
t <- table(x1, x2, dnn = c("Sample A", "Sample B"))
kable(t, caption = "kable table title")
something weird

When echo = false labels on first table, caption from second table before first.

set.seed(2016)
x1 = sample(letters[1:3], 1000, TRUE)
x2 = sample(letters[1:3], 1000, TRUE)
table(x1, x2, dnn = c("Sample A", "Sample B"))
kable(table(x1, x2, dnn = c("Sample A", "Sample B")), caption = "kable table title")

With kable(NULL, ...) and echo = false this kinda looks allright...

set.seed(2016)
x1 = sample(letters[1:3], 1000, TRUE)
x2 = sample(letters[1:3], 1000, TRUE)
table(x1, x2, dnn = c("Sample A", "Sample B"))
kable(NULL, caption = "kable table title")

Any idea how to get them both (labels and caption) working together?

Problem when using ***

I was working with a series of tables and had put a *** between them to get a horizontal line. However this seemed to really destroy the LaTex rendering if there was not a blank line between the preceding code chunk and the ***. (Maybe there is an rmarkdown rule I am unaware of about this?) I just wanted to note it since someone else may come across it.

Missing style?

When knitting the vignette to html, the table formatting is absent (except for the bold text in the table header). Is there supposed to be an additional style sheet?

capture

Rmd partials

I like the concept of Rmd partials for repetitive things I do (like summaries of models, robustness checks, making a codebook for the items in a survey).

But I'm not sure I'm using them right, because it seems a bit hacky at times.

To give an example: here, you can see where I used one to summarise a regression with some plots and headlines (this is a simplified example, it's usually a bit more involved).

The partial itself: https://rubenarslan.github.io/repro_web_stack/_regression_summary.html
Used: https://rubenarslan.github.io/repro_web_stack/3_analyses.html

Here are things that felt a bit hacky:

  • I needed to set options(knitr.duplicate.label = 'allow') globally if I want named chunks.
  • I "needed" this convenience function: https://github.com/rubenarslan/formr/blob/master/R/rmarkdown_options.R#L234 so that it's rendered "asis" and so that the environment is the calling environment for knit_child.
  • I wanted to call the partials from a function (could simply be knit_print.lm or something more "custom" like I use now). So it takes arguments from the calling environment, but I cannot specify these in the Rmd file. I tried using parameters, but I think knitr:knit_child does not support them.

I was thinking of packaging some partials that I've made for myself, but wanted to collect your opinion on best practices first. Should I maybe use an htmlwidget-style approach for this as this is more "standard"? I like about the knit_child approach that I can treat it like text, concatenate several etc.

Error when using summary()

base::summary() causes a fatal error when present in a markdown file with printr.

Reproducible example

     library(printr)  
     summary(iris$Sepal.Length)

generates
Error in provideDimnames(x, sep = sep, base = base) : 'dimnames' applied to non-array Calls: <Anonymous> ... eval -> eval -> data.frame -> do.call -> provideDimnames

dimnames(summary(iris$Sepal.Length)) is NULL

Using as.array(summary(iris$Sepal.Length)) solves it, but it was definitely unexpected by me at least.

"[" trips up printing

```{r help page,  render.args=list(help=list(sections=c('description', 'format')))}
?ToothGrowth
```

produces:

screen shot 2016-09-19 at 12 00 17 pm

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.