Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
462 views
in Technique[技术] by (71.8m points)

r - How to get dimnames in xtable.table output?

I'd like to have the dimensions labeled in my xtable output. However, the table method of xtable does not output dimension labels even when I specify them manually to table:

set.seed(10)
d <- data.frame(x=sample(1:4),y=sample(1:4))
tb <- with(d, table(d,dnn=c("Xs","Ys")))
> tb
   Ys
Xs  1 2 3 4
  1 0 0 0 1
  2 0 1 0 0
  3 1 0 0 0
  4 0 0 1 0
> xtable(tb)
% latex table generated in R 2.15.1 by xtable 1.7-0 package
% Tue Oct  9 09:06:10 2012
egin{table}[ht]
egin{center}
egin{tabular}{rrrrr}
  hline
 & 1 & 2 & 3 & 4 \ 
  hline
1 &   0 &   0 &   0 &   1 \ 
  2 &   0 &   1 &   0 &   0 \ 
  3 &   1 &   0 &   0 &   0 \ 
  4 &   0 &   0 &   1 &   0 \ 
   hline
end{tabular}
end{center}
end{table}

Inspection of the code for xtable.table doesn't yield any secrets. Short of building them manually with multirow is there any way of getting the dimensions labeled?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This doesn't create multirow or multicolumn headers based on the names of the dimensions, but it at least does get them displayed.

print(xtable(format(ftable(tb))), 
      include.rownames=FALSE, include.colnames=FALSE,
      sanitize.text.function = function(x) {gsub('"',"",x)})

which gives

% latex table generated in R 2.15.1 by xtable 1.7-0 package
% Tue Oct 09 11:28:33 2012
egin{table}[ht]
egin{center}
egin{tabular}{llllll}
  hline
  hline
     & Ys & 1 & 2 & 3 & 4 \ 
  Xs &      &     &     &     &     \ 
  1  &      &   0 &   0 &   0 &   1 \ 
  2  &      &   0 &   1 &   0 &   0 \ 
  3  &      &   1 &   0 &   0 &   0 \ 
  4  &      &   0 &   0 &   1 &   0 \ 
   hline
end{tabular}
end{center}
end{table}

You can restore the horizontal lines in the "right" place as well:

print(xtable(format(ftable(tb))), 
      include.rownames=FALSE, include.colnames=FALSE,
      sanitize.text.function = function(x) {gsub('"',"",x)},
      hline.after = c(-1, 2, nrow(tb)+2))

giving

% latex table generated in R 2.15.1 by xtable 1.7-0 package
% Tue Oct 09 11:29:21 2012
egin{table}[ht]
egin{center}
egin{tabular}{llllll}
  hline
      & Ys & 1 & 2 & 3 & 4 \ 
  Xs &      &     &     &     &     \ 
   hline
1  &      &   0 &   0 &   0 &   1 \ 
  2  &      &   0 &   1 &   0 &   0 \ 
  3  &      &   1 &   0 &   0 &   0 \ 
  4  &      &   0 &   0 &   1 &   0 \ 
   hline
end{tabular}
end{center}
end{table}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...