1

我有以下数据框:

> 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. 我正在尝试使用以下代码执行此操作:

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 代码(只是表格内部的一个片段):

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 使用有效数字而不是数字,但这不会改变输出。

有任何想法吗?

4

1 回答 1

6

发生这种情况是因为您的数据包含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}
于 2012-07-18T11:00:47.063 回答