【问题标题】:Ensure all cells have 3 digits in LaTeX representation using xtable使用 xtable 确保所有单元格在 LaTeX 表示中都有 3 位数字
【发布时间】:2012-07-18 10:43:41
【问题描述】:

我有以下数据框:

> dput(py6s_pwc_16)
structure(list(source = c("AERONET", "BIGF", "MODIS"), ndvi_real = c(0.618, 
0.618, 0.618), ndvi_95 = c("0.616", "0.616", "0.615"), ndvi_05 = c("0.62", 
"0.62", "0.621"), perc_95 = c("-0.288", "-0.315", "-0.431"), 
    perc_05 = c("0.374", "0.289", "0.471")), .Names = c("source", 
"ndvi_real", "ndvi_95", "ndvi_05", "perc_95", "perc_05"), row.names = c(NA, 
-3L), class = "data.frame")

当我在 R 命令提示符处打印出来时,它看起来像这样:

> py6s_pwc_16
   source ndvi_real ndvi_95 ndvi_05 perc_95 perc_05
1 AERONET     0.618   0.616    0.62  -0.288   0.374
2    BIGF     0.618   0.616    0.62  -0.315   0.289
3   MODIS     0.618   0.615   0.621  -0.431   0.471

我想使用xtable 生成此表的 LaTeX 表示。我正在尝试使用以下代码执行此操作:

x <- xtable(py6s_pwc_16)
digits(x) <- 3
print(x, include.rownames=FALSE, table.placement=NULL, latex.environments=NULL, size="\\centering", booktabs=TRUE, sanitize.colnames.function=add_bold)

但是,这会产生如下所示的 LaTeX 代码(只是表格内部的一个 sn-p):

AERONET & 0.618 & 0.616 & 0.62 & -0.288 & 0.374

如您所见,第 4 列没有三位数字 - 它只是 0.62,我希望它是 0.620。有没有办法让 xtable 做到这一点?

我已尝试添加该行:

display(x) <- rep("fg", ncol(x)+1)

尝试让 R 使用有效数字而不是数字,但这不会改变输出。

有什么想法吗?

【问题讨论】:

    标签: r latex xtable


    【解决方案1】:

    发生这种情况是因为您的数据包含character,而它应该是numeric

    str(py6s_pwc_16)
    'data.frame':   3 obs. of  6 variables:
     $ source   : chr  "AERONET" "BIGF" "MODIS"
     $ ndvi_real: num  0.618 0.618 0.618
     $ ndvi_95  : chr  "0.616" "0.616" "0.615"
     $ ndvi_05  : chr  "0.62" "0.62" "0.621"
     $ perc_95  : chr  "-0.288" "-0.315" "-0.431"
     $ perc_05  : chr  "0.374" "0.289" "0.471"
    

    要修复它,请将chr 列转换为数字:

    py6s_pwc_16[, 2:6] <- lapply(py6s_pwc_16[2:6], as.numeric)
    

    然后运行xtable:

    library(xtable)
    xtable(py6s_pwc_16, digits=3)
    
    % latex table generated in R 2.15.0 by xtable 1.7-0 package
    % Wed Jul 18 12:00:33 2012
    \begin{table}[ht]
    \begin{center}
    \begin{tabular}{rlrrrrr}
      \hline
     & source & ndvi\_real & ndvi\_95 & ndvi\_05 & perc\_95 & perc\_05 \\ 
      \hline
    1 & AERONET & 0.618 & 0.616 & 0.620 & -0.288 & 0.374 \\ 
      2 & BIGF & 0.618 & 0.616 & 0.620 & -0.315 & 0.289 \\ 
      3 & MODIS & 0.618 & 0.615 & 0.621 & -0.431 & 0.471 \\ 
       \hline
    \end{tabular}
    \end{center}
    \end{table}
    

    【讨论】:

      猜你喜欢
      • 2019-10-07
      • 2013-09-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-25
      • 2020-11-29
      • 2013-12-13
      • 2022-07-11
      相关资源
      最近更新 更多