在格式化位数时转置xtable

时间:2014-02-08 18:41:45

标签: r xtable

我有一个包含2行(前/后处理)和11列的数据帧,我希望将其显示为11x2表。以下工作做得很好:

print(xtable(t(df)))

但是,我无法弄清楚如何控制数字位数并完成转置。是否可以进行后xtable转置?

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?

我在创建xtable之前也尝试过转置,然后单独更改行的数字,但无法使其工作,即。,

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

一般的挑战是在最终表中我需要在同一列中的行之间使用不同的小数位数。这让我觉得可能需要某种版本的第一种方法,以便可以使用标准的xtable数字控件(即Control number of decimal places on xtable output in R

1 个答案:

答案 0 :(得分:2)

一个问题是你的'数字'参数是12项长。取消前导“0”可以减少警告:

 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}

矩阵和data.frames的转置函数似乎强制数字宽度的列均匀性(或者它可能是它们的打印方法?

这是一个非常糟糕的努力:

 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"   
相关问题