2016-11-29 115 views
0

我有這個表,我想在RMD文件中使用PANDOC的PDF渲染色細胞

table = data.frame(category = c("A","B","C"), groupA = c(.2,.3,.5), groupB= c(.6,.7,.9)) 
table 
pandoc.table(table,split.table = Inf,keep.line.breaks = TRUE) 

---------------------------- 
category groupA groupB 
---------- -------- -------- 
    A  0.2  0.6 

    B  0.3  0.7 

    C  0.5  0.9 
---------------------------- 

我怎樣才能顏色的「A組」和「B組」列與細胞條件格式如:

>0 and <= .2 = "green" 
>.2 and <= .3 = "red" 
>.3 and <= .4 = "blue" 
>.4 and <= .5  = "orange" 
>.5 and <= .6  = "yellow" 
>.6 and <= .7  = "black" 
>.7 and <= .8  = "brown" 
>.8 = "white" 
+0

要渲染HTML或PDF?如果是前者,請查看[formattable](https://renkun.me/formattable/)。 – alistaire

+0

becasue它是PDF – user3022875

回答

1

如果您渲染爲PDF,您(或其他人的功能)必須使用LaTeX格式化您的表格。雖然有很多有用的包和功能,將做所有的工作適合你(knitr::kablextablestargazer)的,如果你需要細粒度控制,你可能需要編輯乳膠自己,至少在一部分。

一個合理的無痛選項是Hmisc::latex,它將從data.frame中創建表格,並且有一個參數(衆多中)cellTexCmds,允許通過類似尺寸的矩陣傳遞樣式給data.frame。該file參數''所以它不保存文件,並where = '!htbp'所以表出現在文檔中的正確位置。要設置單元格背景顏色,你需要的xcolorcolortbl LaTeX的包,它可以在YAML frontmatter加載。

爲了消除LaTeX的評論,捕獲輸出,子集和打印,或只是使用的,而不是.Rmd .Rnw。

--- 
title: "Conditional Formatting" 
header-includes: 
    - \usepackage[table]{xcolor} 
output: 
    pdf_document: default 
--- 


```{r} 
df <- data.frame(category = c("A","B","C"), 
       groupA = c(.2,.3,.5), 
       groupB= c(.6,.7,.9)) 

df.format = matrix('', nrow = nrow(df), ncol = ncol(df)) 

df.format[, -1] <- paste0('cellcolor{', 
          sapply(df[-1], function(x){ 
           cut(x, breaks = c(0, seq(.2, .8, by = .1), 1), 
            labels = c('green', 'red', 'blue', 'orange', 
              'yellow', 'black', 'brown', 'white'))}), 
          '}') 

df.format 
``` 

```{r table, results='asis'} 
cat(capture.output(
    Hmisc::latex(df, file = '', cellTexCmds = df.format, where = "!htbp") 
    )[-1]) 
``` 

pdf image with formatted cells

+0

我不能使用formattable我不能有這樣的 「%latex.default(DF,文件=‘’,cellTexCmds = df.format,其中=‘!htbp’)%」 表示。你知道使用rmd的其他選擇嗎? – user3022875

+0

'latex'被設計爲寫入一個文件,所以你可以寫一個文件並用'readLines'導入它,跳過第一行。然而,試圖讓它寫一個文件正在[R掛起我無法解釋的原因,所以也許更簡單的解決方法是捕獲輸出,子集,並打印:'貓(capture.output( Hmisc ::乳膠(DF ,file ='',cellTexCmds = df.format,where =「!htbp」))[ - 1])' – alistaire