Error in applying a for loop to an xtable in knitr

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-23 17:04:03

问题


I'm preparing a pdf using knitr that contains a table produced using xtable. I'm adding a bold typeface to certain cells in the table so I've written the following function:

bold <- function(x, matrix){
        x[] <- lapply(x, as.character)
          for (i in 1:ncol(x)) {   
            yes <- matrix[,i]
              x[yes,i] <- paste('\\textbf{', x[yes,i], '}', sep = "")  
          } 
                print(x, sanitize.text.function = identity)
}

My intention is that the object 'l.mat' is a logical matrix and by changing the 1's and 0's in the matrix I can change which cells are bold.

The function seems to produce the desired result but when I compile the document the 'include.rownames = FALSE' argument in print.xtable does not seem to work and I'm getting the following error printed in the pdf:

TRUE Error in rep(" ", nrow(x) + 2): invalid ’times’ argument  

Here's how I'm creating the matrix I'm using for the logical test:

l.vec <- as.logical(c(1,1,1,1,1,
                      1,1,1,1,1,
                      0,0,0,0,0,
                      0,0,0,0,0,
                      0,0,0,0,0,
                      0,0,0,0,1))

l.mat <- matrix(l.vec, nrow = 6, ncol = 5, byrow = TRUE)

And here's how I'm printing the table:

x.df.2 <- (xtable(df.2))

x.df.3 <- bold(x.df.2, l.mat)

print.xtable(x.df.3, include.rownames = FALSE)

I'm already well out of my depth here and I can't wrap my head around this problem. I feel like I don't understand enough about how xtable, latex and knitr work and interact to understand this error. Any guidance as to what's causing these errors would be very helpful.

Sample data frame:

df.2 <-     DATE   CY   FY Quarter  XEMPNIN
        275 2043:3 2043 2044       3 3324.391
        276 2043:4 2043 2044       4 3326.214
        277 2044:1 2044 2044       1 3328.492
        278 2044:2 2044 2044       2 3330.100
        279 2044:3 2044 2045       3 3331.963
        280 2044:4 2044 2045       4 3334.248

回答1:


You were close. The problem is with your bold() function. Try:

bold <- function(x, matrix) {

  x[] <- lapply(x, as.character)

  for (i in 1:ncol(x)) {   
    yes <- matrix[,i]
    x[yes,i] <- paste('\\textbf{', x[yes,i], '}', sep = "")  
  } 
  return(x)
}

and add the sanitize.text to the print.xtable() call:

print.xtable(
  x.df.3, 
  include.rownames = FALSE, 
  sanitize.text.function = identity
  )

This should give you what you want:

A fully reproducible .Rnw file is available here.



来源:https://stackoverflow.com/questions/30309311/error-in-applying-a-for-loop-to-an-xtable-in-knitr

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