I have a data frame of observation, and I want to export the data frame to a docx
file in the format like the picture. I can do this but in a hard way. Is there any more convenient way? Here are the packages I know that may help:knitr
printr
bookdown
.
Say I have a data frame mydata
like this:
Group CRP PCT
pos 1 7
pos 2 8
pos 3 9
neg 4 10
neg 5 11
neg 6 12
I want the output
like this:
Group CRP PCT
pos 2(1~3) 8(7~9)
neg 5(4~6) 11(10~12)
p-value 0.00 0.00
I think the question is:
mydata
above, how can I transform it easily to output
?output
, how can I export it to docx
same as the format in the picture ?You can use dplyr
to transform your data and tableHTML
to create a table like the one in your question.
library(dplyr)
This function is used to summarise the CRP
and PCT
by GROUP
.
fun <- function(x) {
paste0(x[! x %in% c(min(x), max(x)) ],
"(",
min(x),
"~",
max(x),
")")
}
Use that function in summarise_all()
on mydata
grouped by Group
and sort the data by Group
:
output <- mydata %>%
group_by(Group) %>%
summarise_all(.funs = fun) %>%
arrange(desc(Group))
Then use tableHTML
on output
to create a scientific table:
library(tableHTML)
output %>%
tableHTML(rownames = FALSE,
widths = rep(100, 3),
theme = 'scientific')
The result looks like this: