Question

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)

Was it helpful?

Solution

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