在knitr中将for循环应用于xtable时出错 [英] Error in applying a for loop to an xtable in knitr
问题描述
我正在使用knitr准备一个pdf,其中包含一个使用xtable生成的表.我向表中的某些单元格添加了粗体字,因此我编写了以下函数:
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)
}
我的意图是对象"l.mat"是一个逻辑矩阵,通过更改矩阵中的1和0,我可以更改哪些单元格为粗体.
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.
该函数似乎产生了预期的结果,但是当我编译文档时,print.xtable中的'include.rownames = FALSE'参数似乎不起作用,并且我在pdf中打印了以下错误:>
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)
我已经不在这里了,我无法解决这个问题.我觉得我对xtable,latex和knitr的工作方式以及如何理解该错误的交互方式还不够了解.关于导致这些错误的原因的任何指导都将非常有帮助.
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.
样本数据框:
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()
函数上.试试:
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)
}
并将sanitize.text
添加到print.xtable()
调用中:
print.xtable(
x.df.3,
include.rownames = FALSE,
sanitize.text.function = identity
)
这应该给您您想要的东西:
This should give you what you want:
可以完全复制的.Rnw文件此处.
A fully reproducible .Rnw file is available here.
这篇关于在knitr中将for循环应用于xtable时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!