受保护的空间和R中的$符号用于乳胶提取

时间:2018-10-30 14:18:40

标签: r latex

我按组进行多次回归。根据此coef p值,我只提取出1个附加星号的系数。 她是我的代码示例:

for(i in 1:length(list)) {
    # Equation
    coef <- summary(lm(formula = var1 ~ var2 + var3 + var4,
                       data = subset(data.df, origin==var2[i])
                    ),
            )
    # extraction
    est     <- coef$coefficients[2,1]
    p       <- coef$coefficients[2,4]
    # Define notions for significance levels; spacing is important.
    mystars <- ifelse(p < .001, "***", 
               ifelse(p < .01 , "** ", 
               ifelse(p < .05 , "*  ",
               "   ")))
    # past stars after estimate - put it in the matrix
    est.mat[1,i] <- paste(sprintf('%.2f',est), mystars, sep = "", collapse = NULL)
    # drop useless objects
    rm(coef, est, t, p)
}

这很好用。完成后,将矩阵 est.mat 转移到乳胶中,如下所示:

print(xtable(est.mat, align = c("l","r","r","r","r","r","r"),
                              label = paste("tab:", file.name, sep = "", collapse = NULL),
                              caption = file.caption),
             type = "latex",
             size="\\normalsize",
             caption.placement = "top",
             file = paste("graphs/", file.name, ".tex", sep = "", collapse = NULL) 
     )

它也很好地工作。唯一的问题是,一旦以PDF格式打印,“ mystar”中定义的星号后的空白将被视为“不存在”,因此系数编号未对齐,如下所示。

enter image description here

然后我的问题是:如何在“ mystar”中保护该空间??

1 个答案:

答案 0 :(得分:1)

执行此操作的一种方法是使用“幻像”星,该星与星占据相同的空间,但不显示任何内容。我相信对您的代码进行此修改即可:

mystars <- ifelse(p < .001, "***", 
           ifelse(p < .01 , "**\\phantom{*}", 
           ifelse(p < .05 , "*\\phantom{**}",
           "\\phantom{***}")))

这总是会留出三颗星的空间,因此您可能想通过先查看整列,然后根据该列中最多的星星选择要添加的幻影星星来使其有点幻想。我留给你。

编辑后添加:如Using xtable with R and Latex, math mode in column names?中所述,print.xtable将转义LaTeX宏,因此将显示在生成的PDF中。但是您可以使用参数sanitize.text.function告诉它不这样做:

print(xtable(est.mat, align = c("l","r","r","r","r","r","r"),
                              label = paste("tab:", file.name, sep = "", collapse = NULL),
                              caption = file.caption),
             type = "latex",
             size="\\normalsize",
             caption.placement = "top",
             file = paste("graphs/", file.name, ".tex", sep = "", collapse = NULL), 
             sanitize.text.function = function(x) x
     )

这假定所有表条目都是合法的LaTeX。如果不是这样,您可能需要进行更复杂的消毒。