将for循环应用于knitr中的xtable时出错

将for循环应用于knitr中的xtable时出错,r,latex,knitr,xtable,R,Latex,Knitr,Xtable,我正在使用knitr准备一个pdf,其中包含一个使用xtable生成的表。我在表中的某些单元格中添加了粗体字体,因此我编写了以下函数: bold <- function(x, matrix){ x[] <- lapply(x, as.character) for (i in 1:ncol(x)) { yes <- matrix[,i] x[yes,i] <- paste('\\t

我正在使用knitr准备一个pdf,其中包含一个使用xtable生成的表。我在表中的某些单元格中添加了粗体字体,因此我编写了以下函数:

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)
}
下面是我如何创建用于逻辑测试的矩阵:

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)

l.vec你很接近。问题在于
bold()
函数。尝试:

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)
}
这将为您提供您想要的:


可以使用完全可复制的.Rnw文件。

非常感谢!我真不敢相信我离得这么近,我确信自己有一些复杂的针头/乳胶问题。
x.df.2 <- (xtable(df.2))

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

print.xtable(x.df.3, include.rownames = FALSE)
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
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)
}
print.xtable(
  x.df.3, 
  include.rownames = FALSE, 
  sanitize.text.function = identity
  )