Pregunta

Estoy usando el paquete dprint con knitr, principalmente para que pueda resaltar filas de una tabla, que tengo trabajo, pero la imagen de salida deja un espacio bastante grande para una nota al pie, y está ocupando espacio innecesario.

está ahí lejos para deshacerse de ella?

También, dado que soy bastante nuevo en Dprint, si alguien tiene mejores ideas / sugerencias sobre cómo resaltar las tablas y hacer que se vean bonitas sin ninguna pista a pie de página ... o formas de ordenar mi código que sería genial!

Un ejemplo del código de archivo RMD está debajo ...

```{r fig.height=10, fig.width=10, dev='jpeg'}
library("dprint")
k <- data.frame(matrix(1:100, 10,10))
CBs <- style(frmt.bdy=frmt(fontfamily="HersheySans"), frmt.tbl=frmt(bty="o", lwd=1),
        frmt.col=frmt(fontfamily="HersheySans", bg="khaki", fontface="bold", lwd=2, bty="_"),
        frmt.grp=frmt(fontfamily="HersheySans",bg="khaki", fontface="bold"),
        frmt.main=frmt(fontfamily="HersheySans", fontface="bold", fontsize=12),
        frmt.ftn=frmt(fontfamily="HersheySans"),
        justify="right", tbl.buf=0)

x <- dprint(~., data=k,footnote=NA, pg.dim=c(10,10), margins=c(0.2,0.2,0.2,0.2), 
              style=CBs, row.hl=row.hl(which(k[,1]==5), col='red'), 
               fit.width=TRUE, fit.height=TRUE,  
                showmargins=TRUE, newpage=TRUE, main="TABLE TITLE")

```

¡Gracias de antemano!

¿Fue útil?

Solución 2

Así que aquí está mi solución ... con algunos ejemplos ...

Acabo de copiar y pegado mi archivo RMD para demostrar cómo usarlo.

Debe poder copiarlo y pegarlo en un archivo RMD en blanco y luego quédate a HTML para ver los resultados ...

Idealmente lo que me hubiera gustado habría sido para hacerlo toda una buena función limpia en lugar de dividirla en dos (es decir, Setup.table & print.table), pero como las opciones de los trozos no se pueden cambiar la mitad del trozo, como se sugierepor Yihui , tenía que dividirse en dos funciones..

`dprint` +  `knitr` Examples to create table images
===========

```{r}
library(dprint)
# creating the sytle object to be used
CBs <- style(frmt.bdy=frmt(fontfamily="HersheySans"), 
             frmt.tbl=frmt(bty="o", lwd=1),
        frmt.col=frmt(fontfamily="HersheySans", bg="khaki", 
                      fontface="bold", lwd=2, bty="_"),
        frmt.grp=frmt(fontfamily="HersheySans",bg="khaki", 
                      fontface="bold"),
        frmt.main=frmt(fontfamily="HersheySans", fontface="bold", 
                       fontsize=12),
        frmt.ftn=frmt(fontfamily="HersheySans"),
        justify="right", tbl.buf=0)

# creating a setup function to setup printing a table (will probably put this function into my .Rprofile file)
setup.table <- function(df,width=10, style.obj='CBs'){
  require(dprint)
  table.style <- get(style.obj)
  a <- tbl.struct(~., df)
  b <- char.dim(a, style=table.style)
  p <- pagelayout(dtype = "rgraphics", pg.dim = NULL, margins = NULL)
  f <- size.simp(a[[1]], char.dim.obj=b, loc.y=0, pagelayout=p)
  # now to work out the natural table width to height ratio (w.2.h.r) GIVEN the style
  w.2.h.r <- as.numeric(f$tbl.width/(f$tbl.height +b$linespace.col+ b$linespace.main))
  height <- width/w.2.h.r

  table.width <- width
  table.height <- height

  # Setting chunk options to have right fig dimensions for the next chunk
  opts_chunk$set('fig.width'=as.numeric(width+0.1))
  opts_chunk$set('fig.height'=as.numeric(height+0.1))

  # assigning relevant variables to be used when printing
  assign("table.width",table.width, envir=.GlobalEnv)
  assign("table.height",table.height, envir=.GlobalEnv)
  assign("table.style", table.style, envir=.GlobalEnv)
}

# function to print the table (will probably put this function into my .Rprofile file as well)
print.table <- function(df, row.2.hl='2012-04-30', colour='lightblue',...) {
  x <-dprint(~., data=df, style=table.style, pg.dim=c(table.width,table.height), ..., newpage=TRUE,fit.width=TRUE, row.hl=row.hl(which(df[,1]==row.2.hl), col=colour))
}
```

```{r}
# Giving it a go!
# Setting up two differnt size tables
small.df <- data.frame(matrix(1:100, 10,10))
big.df <- data.frame(matrix(1:800,40,20))
```


```{r}
# Using the created setup.table function
setup.table(df=small.df, width=10, style.obj='CBs')
```

```{r}
# Using the print.table function
print.table(small.df,4,'lightblue',main='table title string') # highlighting row 4
```

```{r}
setup.table(big.df,13,'CBs') # now setting up a large table
```

```{r}
print.table(big.df,38,'orange', main='the big table!') # highlighting row 38 in orange
```

```{r}
d <- style() # the default style this time will be used
setup.table(big.df,15,'d')
```

```{r}
print.table(big.df, 23, 'indianred1') # this time higlihting row 23
```

Otros consejos

No he usado dprint antes, pero veo un par de cosas diferentes que podrían estar causando problemas:

  • El inicio de su código de código ha definido el ancho y la altura de la imagen, lo que dprint parece estar tratando de usar.
  • Usted está estableciendo tanto fit.height como fit.width. Creo que solo se usa uno de esos (en otras palabras, la imagen resultante no se estira para adaptarse a tanto altura y anchura, pero solo la que parece tener la mayoridad, en este caso, ancho ).

    Después de jugar por un minuto, esto es lo que hice que minimiza la nota al pie. Sin embargo, no sé si hay una forma más eficiente de hacer esto.

    ```{r dev='jpeg'}
    library("dprint")
    k <- data.frame(matrix(1:100, 10,10))
    CBs <- style(frmt.bdy=frmt(fontfamily="HersheySans"), 
                 frmt.tbl=frmt(bty="o", lwd=1),
            frmt.col=frmt(fontfamily="HersheySans", bg="khaki", 
                          fontface="bold", lwd=2, bty="_"),
            frmt.grp=frmt(fontfamily="HersheySans",bg="khaki", 
                          fontface="bold"),
            frmt.main=frmt(fontfamily="HersheySans", fontface="bold", 
                           fontsize=12),
            frmt.ftn=frmt(fontfamily="HersheySans"),
            justify="right", tbl.buf=0)
    
    x <- dprint(~., data=k, style=CBs, pg.dim = c(7, 4.5), 
                showmargins=TRUE, newpage=TRUE, 
                main="TABLE TITLE", fit.width=TRUE)
    
    ```
    

    Actualización

    Jugando para determinar los tamaños de las imágenes es un arrastre total. Pero, si ejecuta el código en R y busca la estructura del x, encontrará lo siguiente:

    str(x)
    # List of 3
    #  $ cord1  : num [1:2] 0.2 6.8
    #  $ cord2  : Named num [1:2] 3.42 4.78
    #   ..- attr(*, "names")= chr [1:2] "" ""
    #  $ pagenum: num 2
    

    o, simplemente:

    x$cord2
    
    # 3.420247 4.782485 
    

    Estas son las dimensiones de su imagen resultante, y esta información probablemente se puede conectar fácilmente a una función para mejorar sus parcelas.

    buena suerte!

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top