Search code examples
rpresentation

Presenting very small numbers in R effectively


Imagine this table, where each row is a different variable, and columns are the Coefficient and P-Values:

           Coef       P-Value
 [1,] -0.0005017369 1.787221e-03
 [2,] -0.0096543344 0.000000e+00

When I use xtable to insert in latex xtable(table,digits=3) i get this:

\begin{table}[ht]
\centering
\begin{tabular}{rrr}
  \hline
 & 1 & 2 \\ 
  \hline
1 & -0.001 & 0.002 \\ %you can see it rounds the coefs and I don't want that
  2 & -0.010 & 0.000 \\ 
   \hline
\end{tabular}
\end{table}

However some coeffs are very small: 0.000001, for example. What I am trying to do is present the results like this:

           Coef       
 [1,] -5.01 e^-4 (***)
 [2,] -9.65 e^-3 (***)

With (***) when P-Value < 0.01 
      (**) when 0.01 < P-V < 0.05 and
       (*) when 0.05 < P-V < 0.1

Here is some data for the example:

coeffs<-c(-0.0813492327 ,-0.0096543344 ,-1.0854510145 , 0.0114780266 ,-0.0018292747, -0.1953482934 ,-0.0370855156,  0.0643568136,
-0.1113654966, -0.0043410195,  0.0092573323, -0.0001360552, -0.0001318953, -0.0001374126, -0.0005017369) ,
pv<-c(1.955660e-02, 0.000000e+00, 0.000000e+00, 7.960061e-01, 7.435434e-01, 6.699631e-06, 6.260328e-01, 1.012333e-01, 4.201014e-05,
0.000000e+00, 1.056896e-06, 3.664292e-01, 4.465335e-01, 3.745726e-01, 1.787221e-03)

Solution

  • For using scientific notation in xtable, you need to use negative numbers in the digits option.

    Part of the documentation for the digits option of xtable:

    If values of digits are negative, the corresponding values of x are displayed in scientific format with abs(digits) digits.

    Example:

    xtable::xtable(data.frame(coeffs, pv), digits = -2)
    
    \begin{table}[ht]
    \centering
    \begin{tabular}{rrr}
      \hline
     & coeffs & pv \\ 
      \hline
    1 & -8.13E-02 & 1.96E-02 \\ 
      2 & -9.65E-03 & 0.00E+00 \\ 
      3 & -1.09E+00 & 0.00E+00 \\ 
      4 & 1.15E-02 & 7.96E-01 \\ 
      5 & -1.83E-03 & 7.44E-01 \\ 
      6 & -1.95E-01 & 6.70E-06 \\ 
      7 & -3.71E-02 & 6.26E-01 \\ 
      8 & 6.44E-02 & 1.01E-01 \\ 
      9 & -1.11E-01 & 4.20E-05 \\ 
      10 & -4.34E-03 & 0.00E+00 \\ 
      11 & 9.26E-03 & 1.06E-06 \\ 
      12 & -1.36E-04 & 3.66E-01 \\ 
      13 & -1.32E-04 & 4.47E-01 \\ 
      14 & -1.37E-04 & 3.75E-01 \\ 
      15 & -5.02E-04 & 1.79E-03 \\ 
       \hline
    \end{tabular}
    \end{table}