R to latex - Coloring numbers automatically

泄露秘密 提交于 2019-12-11 09:08:28

问题


I have a (long) R matrix. eg:

matrix <- matrix(rexp(200, rate=.01), ncol=4)

I would like to find a way to colour, for instance, the 15% more important numbers of each column, BEFORE doing the latex extraction as follow:

print(xtable(matrix, align = c("r","r","r","r","r")),
type = "latex",
floating = FALSE,
tabular.environment = "longtable")

Any idea?


回答1:


I finally found a dirty solution

matrix <- as.data.frame(matrix(rexp(200, rate=.01), ncol=4))

Set the loop

for(i in 1:length(matrix[1,])) {
quant  <- quantile(matrix[,i], prob = 0.85, na.rm = TRUE)   
   for(j in 1:length(matrix[,1])) {         
       if(as.numeric(matrix[j,i]) > quant) {
       matrix[j,i] <- paste("\\cellcolor{red!25}", matrix[j,i], sep="", collapse = NULL)} 
       else {}  
} } # close both loops

Then print the result in latex

print(xtable(matrix), 
      type = "latex",
      sanitize.text.function = identity)

It give an acceptable result. It is important to set: "quant <- quantile" before the "j" loop. If not the change made during this "j" loop change matrix[,i] into a character vector and it is then impossible to re-compute the quantile.

Don't forget "sanitize.text.function = identity" in the print.



来源:https://stackoverflow.com/questions/53123856/r-to-latex-coloring-numbers-automatically

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!