I'm using R Markdown and am trying to generate a table and centre it in a word document. Below is the code i have taken from github as a test
Table \#ref(tab:table-single) is a simple example.
```{r table-single, tidy=FALSE}
knitr::kable(
head(mtcars, 10), booktabs = TRUE,
caption = 'A table of the first 10 rows of the mtcars data.'
)
```
When i run this piece of code the table name never resolves so i get \#ref(tab:table-single) instead of Table 2.1 as can be seen from the final document
Can someone see where in my code i have made a mistake in relation to referencing my table
I am knitting to MS Word
Thanks
If you use the bookdown package to render your markdown, you will get proper cross-referencing:
---
output: bookdown::word_document2
---
Table \#ref(tab:table-single) is a simple example.
```{r table-single, tidy=FALSE}
knitr::kable(
head(mtcars, 10), booktabs = TRUE,
caption = 'A table of the first 10 rows of the mtcars data.'
)
```
Related
The table prints nicely in markdown but is not present in the knitted html file. I noticed that it is classified as a list but don't know how to change it to an acceptable file type. The knitted output is not formatted as a table. I appreciate the help.
library("crosstable") #important package crosstable() function
library('dplyr')
library("flextable")
tbl1 = crosstable(mtcars2, c(1), by = 2) %>%
as_flextable(keep_id=FALSE)
print(tbl1)
According to ?print.flextable
Note also that a print method is used when flextable are used within R markdown documents. See knit_print.flextable().
Therefore, if we want to print in Rmarkdown, either use knitr::knit_print or remove the print as the ?knit_print.flextable documentation shows
You should not call this method directly. This function is used by the knitr package to automatically display a flextable in an "R Markdown" document from a chunk.
---
title: "Testing"
author: "akrun"
date: "09/12/2021"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
```{r, echo = FALSE}
suppressPackageStartupMessages(library("crosstable")) #important package crosstable() function
suppressPackageStartupMessages(library('dplyr'))
suppressPackageStartupMessages(library("flextable"))
tbl1 = crosstable(mtcars2, c(1), by = 2) %>%
as_flextable(keep_id=FALSE)
# either use knit_print or remove the print wrapper
#knitr::knit_print(tbl1)
tbl1
```
-output
I want to create a .docx report with {officedown}, but instead of using "bookmark" reference types for cross-referencing my tables and figures as suggested in ch.4.6 and ch.4.7 of the User Documentation, I would like my references to be actual "Figure" and "Table" reference types in the resulting .docx. As discussed in this stackoverflow post, this would require {SEQ Figure \\* arabic} and {SEQ Table \\* arabic} word fields and the answers show how to implement this via officer::slip_in_seqfield() or crosstable::body_add_table_legend().
However, I think, these approaches to obtain actual "Figure" and "Table" reference types only work for the {officer} syntax and not the {officedown} syntax. To be clear, so far I understood
{officer} syntax as an R-script that makes use of a dplyr chain that starts with read_docx() %>% [example]
{officedown} syntax as an Rmd-script that makes use of block_caption() and run_autonum() within a chunk [example]
(please correct me if I am wrong)
Therefore, I would like to know whether there is a way to modify the suggested approach in {officedown} in order to obtain actual "Figure" and "Table" reference types that I can also cross-reference in the text. Below is an example using the standard suggested approach:
You can also make use of the `run_autonum()` and `block_caption()` functions
of the {officer} package. Here are the cross references to Table \#ref(tab:tabmtcars2)
and Figure \#ref(fig:figmtcars2). This approach can be used for tables and figures
and the corresponding reference type in MS Word will always be "bookmark".
```{r}
# Table
run_autonum(seq_id = "tab",
bkm = "tabmtcars2") %>%
block_caption(autonum = .,
label = "mtcars table",
style = "Table Caption")
head(mtcars)
# Figure
ggplot(head(mtcars), aes(x = mpg, y = hp)) +
geom_point() + theme_bw()
run_autonum(seq_id = "fig",
bkm = "figmtcars2") %>%
block_caption(autonum = .,
label = "mtcars figure",
style = "Image Caption")
```
This is my first time posting here, so sorry if I get formatting/etc. incorrect. But if I understand you correctly, officer::run_reference may be what you are looking for. Thomas de Marchin gives a really helpful example of this here.
The essence of this is to use block_caption with officer::run_autonum in your r code block, and then use officer::run_reference in the markdown in the place of \#ref(tab:some-tab) as follows:
```{r}
block_caption(label = 'The Caption',
style = 'Table Caption',
autonum = officer::run_autonum(seq_id = 'tab', bkm = 'some-tab'))
head(mtcars) %>% flextable()
```
This is a reference to Table `r officer::run_reference('some-tab')`
As you can read in crosstable's vignette (https://danchaltiel.github.io/crosstable/articles/crosstable-report.html),
you can use this syntax:
---
title: "mtcars"
output: bookdown::word_document2
---
```{r setup, include=FALSE}
library(crosstable)
library(flextable)
library(ggplot2)
```
Table iris is given in Table \#ref(tab:tabmtcars2).
```{r tbl, echo=FALSE, results='asis'}
cat("<caption> (\\#tab:tabmtcars2) Table Iris </caption> \n\r ")
head(mtcars) %>% flextable
```
A figure about mtcars is given in Figure \#ref(fig:tabmtcars).
```{r fig, echo=FALSE, results='asis'}
cat("<caption> (\\#fig:tabmtcars) Figure of mtcars heard </caption> \n\r ")
ggplot(head(mtcars), aes(x = mpg, y = hp)) +
geom_point() + theme_bw()
```
The numbering will be correct, but it won't create any MS Word field, so you will not be able to include these bookmarks in a figure summary, for instance.
I'm not aware of any way to include such fields using Rmarkdown, but you could use the officer syntax (described in the same link) in a plain R script.
This is what Im doing to generate a markdown so that all the things should be in one place.
How can i put these output into a datatable form which are more readable and easier to search.The list which is made are of different length. Each list has a series of table under it.
If there a way to convert these differing length list to data table format that would be really helpful
The table looks like this
## Prepare for analyses
```{r,warning=FALSE,message=FALSE}
set.seed(1234)
library(europepmc)
library(tidypmc)
library(tidyverse)
#library(dplyr)
```
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
```
##Cytarabine cytogenetically normal aml adult clinical trial Randomized Controlled Trial. 828 records found, showing 10
```{r,include=FALSE}
b <-epmc_search(query = 'cytarabine cytogenetically normal aml adult clinical trial Randomized Controlled Trial OPEN_ACCESS:Y',limit = 10)
pmcids <- b$pmcid[b$isOpenAccess=="Y"]
docs <- map(pmcids, epmc_ftxt)
my_tables <- map(docs, pmc_table)
```
```{r}
names(my_tables) <- pmcids
```
The code chunk input and output is then displayed as follows:
```{r basicconsole}
source("flat.R")
L1 <- flattenlist(my_tables)
l.f <- Filter(function(a) any(!is.na(a)), L1)
l.f
#tibble:::print.tbl_df(head(df))
#n <- paste0("Valporic_", names(l.f), ".txt")
for (i in 1:length(l.f)) {
write.table(l.f[i], sep = "\t",row.names = FALSE,col.names = TRUE,file=paste0(names(l.f)[i], ".txt"))
}
UPDATE
I have manged to covert those tibble into dataframe
using this solution
##Outout
```{r}
abc <- mapply(cbind, l.f)
abc
But when it is rendered in the markdown the column formatting is gone. Now i have now dataframe inside list.
But still im not sure how to put that into a data table
**UPDATE 2.0 **
The better approach is to read those saved output as list of files into data table and then use it as markdown but so far it is taking only one ID only. My code.
tbl_fread <-
list.files(pattern = "*.txt") %>%
map_df(~fread(.))
knitr::kable(head(tbl_fread), "pipe")
Is it possible to put these files as such.
if a list of file are from one PMCID then those would be all in one column such as if PMCID one has 3 output then all of them should be one the same row. Then the next PMCID in the second one etc etc.
UPDATE new
I have managed to align the output into more readable format. But It seems that by default all the files assigned to multiple columns which would be the case given that im reading all the files together since my idea of using the list to data table didn't work.
If i can push or stack each unique PMCID over one another instead of all in one after another that would be. Good
knitr::kable(tbl_fread, align = "lccrr")
This may be something you can adapt for R Markdown. I'm not sure what the rationale is to save and load the tables. Instead, you could obtain the tables and show in html directly.
As you are using HTML, make sure to have results='asis' in your chunk. You can use a for loop and seq_along to show each table. You can include information in your table caption, such as the PMCID as well as table number.
---
title: "test13121"
author: "Ben"
date: "1/31/2021"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
# Libraries
```{r}
library(tidypmc)
library(tidyverse)
library(europepmc)
library(kableExtra)
```
# Get Articles
```{r, echo = FALSE}
b <-epmc_search(query = 'cytarabine aml OPEN_ACCESS:Y',limit = 6)
pmcids <- b$pmcid[b$isOpenAccess=="Y"]
docs <- map(pmcids, epmc_ftxt)
my_tables <- map(docs, pmc_table)
names(my_tables) <- pmcids
```
# Show Tables
```{r, echo=F, results='asis'}
for (i in seq_along(my_tables)) {
for (j in seq_along(my_tables[[i]])) {
print(kable(x = my_tables[[i]][[j]], caption = paste0(names(my_tables)[i], ": Table ", j)))
}
}
```
I am working on an R Markdown document that can be downloaded from a Shiny App as a pdf. I have structured my 1-page document with a layout that presents two columns at the beginning and then again one column until the end.
The main issue is that in one of the two columns I can't insert a table generated, for example, through the kable() function of the knitr package, because I get the following error:
Package longtable Error: longtable not in 1-column mode
Below you can find some reproducible code:
---
output: pdf_document
header-includes:
- \usepackage{multicol}
- \newcommand{\btwocol}{\begin{multicols}{2}}
- \newcommand{\etwocol}{\end{multicols}}
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE, cache = T)
library(ggplot2)
library(knitr)
```
\btwocol
#### Column one
```{r}
ggplot(mtcars,
aes(x = mpg,
y = cyl)) +
geom_point()
```
\columnbreak
#### Column two
```{r}
kable(mtcars[1:10, 1:2], format = "markdown")
```
\etwocol
Note that if you remove the kable() function the script can be compiled but the table is in the standard "R" format.
Thanks!
Very simple solution: use from the kableExtra library kbl(df, longtable=F) to produce a table that is not of the longtable format.
I found a solution by using the functionalities of the grid, gridExtra and gtable package. I created and customised the table and its caption directly inside a chunk of the R Markdown file, and with the grid.draw() function I created a graphical object of that table that can now be inserted inside a two-columns layout.
I'm making weighted tables of row proportions using the questionr package. I want to wrap the column names when they are too long. Because I'm making hundreds of tables, the solution needs to work on tables with varying numbers of columns. I also want to avoid setting all columns to a specific width. Ideally, short column names would remain at their normal width while names exceeding the specified maximum length would be wrapped.
Here are a bunch of solutions I've tried so far, written as .Rmd file:
---
title: "Example"
output: pdf_document
---
```{r setup, include=FALSE}
library(questionr)
library(knitr)
data("happy")
```
A simple weighted table with the "kable" method:
```{r table1, echo=TRUE}
kable(wtd.table(happy$degree, happy$happy, weights = happy$wtssall),
digits = 0)
```
The same "kable" table, but with row proportions:
```{r table2, echo=TRUE}
kable(rprop(wtd.table(happy$degree, happy$happy, weights = happy$wtssall)),
digits = 0)
```
I want to wrap the column headers, but kableExtra::column_spec() gives an error.
Even if it worked it requires manually setting each column width.:
```{r table3, echo=TRUE}
library(kableExtra)
kable(rprop(wtd.table(happy$degree, happy$happy, weights = happy$wtssall)),
digits = 0) %>%
column_spec(column = 2, width = ".25in")
```
Maybe str_wrap will do the trick?
```{r table4, echo=TRUE}
library(stringr)
kable(rprop(wtd.table(happy$degree, str_wrap(happy$happy, width = 8),
weights = happy$wtssall)),
digits = 0)
```
Giving up on knitr::kable(), maybe pander has a solution.
Here is the simple weighted frequency table.
```{r table5, echo=TRUE, results='asis'}
library(pander)
pandoc.table(wtd.table(happy$degree, str_wrap(happy$happy, width = 8),
weights = happy$wtssall),
split.cells=8)
```
So far, so good. But it doesn't work for the table of row proportions,
because the rprop table is of class ([1]"proptab" [2]"table")
while the wtd.table() is just class "table"
```{r table6, echo=TRUE, results='asis', error=TRUE}
pandoc.table(rprop(wtd.table(happy$degree, str_wrap(happy$happy, width = 8),
weights = happy$wtssall)),
split.cells=8)
```
But wait! I can pass a kable() product as pandoc output.
This table looks great, but I don't think I pass any
pandoc.table() arguments like "split.cells=8" to it.
```{r table7, echo=TRUE, results='asis', error=TRUE}
kable(rprop(wtd.table(happy$degree, happy$happy, weights = happy$wtssall)),
digits = 0, format = "pandoc")
```
And here is what the output of that .Rmd file looks like:
At least, for kableExtra, you need to specify format in your kable function to be either latex or html.
To make it dynamic, you can save the table to a variable before it goes into kable and use 2:(ncol(your_table) + 1) in the column_spec function (+1 for the column_name column).