Question

I have the following dataframe:

> 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")

When I just print it out at the R command prompt it looks like this:

> 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

I want to produce a LaTeX representation of this table using xtable. I'm trying to do this with the following code:

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)

However, that produces LaTeX code which looks like the following (just a snippet from inside the table):

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

As you can see, the 4th column doesn't have three digits - it's just 0.62, and I'd like it to be 0.620. Is there a way to make xtable do this?

I've tried adding the line:

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

to try and get R to use significant figures rather than digits, but that doesn't change the output.

Any ideas?

Was it helpful?

Solution

This happens because your data contains character where it should be 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"

To fix it, convert the chr columns to numeric:

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

Then run 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}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top