0

I have a dataframe with 2 rows (pre/post treatment) and 11 columns that I want to display as an 11x2 table. The following does the job nicely:

print(xtable(t(df)))

However, I can't figure out how to control the number of digits and also accomplish the transpose. Is a post-xtable transpose possible?

df <- xtable(df)
digits(df) <- c(0,0,0,1,0,1,2,0,1,0,0,2)
t(df) # Does not work; is a post-xtable transpose possible?

I've also tried transposing before creating the xtable, then changing digits for the rows individually, but couldn't get that to work either, i.e.,

df <-xtable(t(df)) # works as intended
digits(df[10,]) <- c(0,1,1) # no error, but does nothing

The general challenge is that in the final table I need a different number of decimals across rows in the same column. This makes me think that some version of the first approach is likely required so that the standard xtable digits controls can be used (i.e., Control number of decimal places on xtable output in R)

Community
  • 1
  • 1
Bryan
  • 1,771
  • 4
  • 17
  • 30

1 Answers1

2

One problem is that your 'digits' argument is 12 items long. Taking off the leading "0" allows warnings to be reduced:

 df <- as.data.frame(matrix(rnorm(22), nrow=2))
 print(xtable(t( mapply("format", df, digits=c(0,0,1,0,1,2,0,1,0,0,2)))))

% latex table generated in R 3.0.2 by xtable 1.7-1 package
% Sat Feb  8 11:37:06 2014
\begin{table}[ht]
\centering
\begin{tabular}{rll}
  \hline
 & 1 & 2 \\ 
  \hline
V1 & 0 & 0 \\ 
  V2 & 0 & 1 \\ 
  V3 &  2.1 & -0.5 \\ 
  V4 & -2 &  1 \\ 
  V5 & -0.7 & -0.7 \\ 
  V6 &  1.03 & -0.28 \\ 
  V7 & -1 &  0 \\ 
  V8 & -0.139 &  0.006 \\ 
  V9 &  0 & -0 \\ 
  V10 &  1 & -0 \\ 
  V11 & 0.33 & 1.10 \\ 
   \hline
\end{tabular}
\end{table}

The transpose functions for matrices and data.frames seem to enforce column uniformity of digit width (or perhaps it is their print methods?

Here's a really kludgy effort:

 capture.output(apply(cbind(t(df), digits), 1, function(x) 
                                            cat( c(round( x[1:2], x[3]) ,"\n") ) )  )
 [1] "0 0 "        "0 1 "        "2.1 -0.5 "   "-2 1 "       "-0.7 -0.7 " 
 [6] "1.03 -0.28 " "-1 0 "       "-0.1 0 "     "0 0 "        "1 0 "       
[11] "0.33 1.1 "   "NULL"   
IRTFM
  • 258,963
  • 21
  • 364
  • 487
  • Thanks, this does the trick. Interestingly though, the `digits` argument appears to function differently in your example than it does for xtable: for "format" it equals the total # of desired digits, whereas for xtable it equals the desired number of digits to the right of the decimal point. – Bryan Feb 08 '14 at 21:10
  • I think it's giving a minimum number of significant digits on a row-basis. – IRTFM Feb 08 '14 at 21:44