Reputation: 61
I want to export my outputs from R to latex using xtable. In addition, I want each of the tables to have an estimate and its standard error. How do I get the elements of a particular row of the matrix in box brackets in R?
The expected output by applying function xtable to the resulting data frame should be as follows:
\begin{tabular}{lcccc}
\hline
& Hi & MV & Zi & Pi \\
\hline
Mean & 0.57 & 0.50 & 0.54 & 0.42 \\
& [0.01] & [0.01] & [0.01] & [0.05] \\
Median & 0.57 & 0.50 & 0.54 & 0.42 \\
& [0.01] & [0.01] & [0.01] & [0.05] \\
MSE & 0.08 & 0.02 & 0.05 & 0.16 \\
& [0.01] & [0.00] & [0.01] &[ 0.04] \\
\hline
\end{tabular}
Thank you.
Upvotes: 3
Views: 1579
Reputation: 77116
you could try this,
x<-matrix(1:12,nrow=4)
bracket <- function(x, i, j){
x[i,j] <- sprintf("[%s]", x[i,j])
x
}
# x <- bracket(x, 2, 3) # test
# every second row
ind = which(row(x) %% 2 == 1, arr.ind = TRUE)
x <- bracket(x, ind[,1], ind[,2])
print(xtable(x), sanitize.text.function = I)
Note: I would probably define a LaTeX macro, e.g. \newcommand{\wrap}[1]{\ensuremath{\left[#1\right]}}
, with x[i,j] <- sprintf("\\wrap{%s}", x[i,j])
in the R code.
Upvotes: 2
Reputation: 61
I found this works for my case but then may be some one can come up with a more efficient way. Suppose, I want to put square brackets on elements in the odd rows, then this miniature program works:
x<-matrix(1:12,4,byrow=TRUE)
y<-matrix(NA,ncol=ncol(x),nrow=nrow(x))
Y<-t(sapply(1:nrow(x),function(i){
if(i%%2!=0){y[i,]<-x[i,]
}else{
y[i,]<-paste0("[",x[i,],"]")
}
}))
print(xtable(Y))
Upvotes: 0