R to latex - 自动着色数字

R to latex - Coloring numbers automatically

我有一个(长)R 矩阵。例如:

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

我想找到一种方法来着色,例如,每列的 15% 更重要的数字, 进行乳胶提取之前:

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

有什么想法吗?

我终于找到了一个肮脏的解决方案

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

设置循环

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

然后在latex中打印结果

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

它给出了一个可以接受的结果。在 "j" 循环之前设置:"quant <- quantile" 很重要。如果不是在此 "j" 循环期间所做的更改,会将 matrix[i] 更改为字符向量,然后就不可能重新计算分位数。

不要忘记打印 "sanitize.text.function = identity"。