How can I produce report quality tables from R?

喜你入骨 提交于 2019-12-12 08:15:13

问题


If I have the following dataframe called result

> result
     Name       CV      LCB       UCB
1  within 2.768443 1.869964  5.303702
2 between 4.733483 2.123816 18.551051
3   total 5.483625 3.590745 18.772389

> dput(result,"")
structure(list(Name = structure(c("within", "between", "total"
), .rk.invalid.fields = list(), .Label = character(0)), CV = c(2.768443, 
4.733483, 5.483625), LCB = c(1.869964, 2.123816, 3.590745), UCB = c(5.303702, 
18.551051, 18.772389)), .Names = c("Name", "CV", "LCB", "UCB"
), row.names = c(NA, 3L), class = "data.frame")

What is the best way to present this data nicely? Ideally I'd like an image file that can be pasted into a report, or possibly an HTML file to represent the table?

Extra points for setting number of significant figures.


回答1:


I would use xtable. I usually use it with Sweave.

library(xtable)
d <- data.frame(letter=LETTERS, index=rnorm(52)) 
d.table <- xtable(d[1:5,])
print(d.table,type="html")

If you want to use it in a Sweave document, you would use it like so:

<<label=tab1,echo=FALSE,results=tex>>=
xtable(d, caption = "Here is my caption", label = "tab:one",caption.placement = "top")
@



回答2:


For the table aspect, the xtable package comes to mind as it can produce LaTeX output (which you can use via Sweave for professional reports) as well as html.

If you combine that in Sweave with fancy graphs (see other questions for ggplot examples) you are almost there.




回答3:


library(ggplot2)
ggplot(result, aes(x = Name, y = CV, ymin = LCB, ymax = UCB)) + geom_errorbar() + geom_point()
ggplot(result, aes(x = Name, y = CV, ymin = LCB, ymax = UCB)) + geom_pointrange()



回答4:


Can't comment on making a pretty table, but to set the significant figures, the easiest thing to do (for this sample data, mind you) would be to move Name to rownames and round the whole thing.

#Set the rownames equal to Name - assuming all unique
rownames(result) <- result$Name  
#Drop the Name column so that round() can coerce
#result.mat to a matrix
result.mat <- result[ , -1]       
round(result.mat, 2) #Where 2 = however many sig digits you want.            

This is not a terribly robust solution - non-unique Name values would break it, I think, as would other non-numeric columns. But for producing a table like your example, it does the trick.



来源:https://stackoverflow.com/questions/1407680/how-can-i-produce-report-quality-tables-from-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!