Data Table cross label in rmarkdown - r

When I call datatable in an r chunk in rmarkdown, the caption is labeled as a figure and I can only cross-reference it as a figure. e.g.
tab_data <- read.csv("localfile.csv")
tab_data %>%
DT::datatable(arguments)
The caption will have a Figure label instead of Table. Is there a way to change the label to Table

This appears to be a known issue with no straight forward answer. see this for more discussion : https://github.com/rstudio/bookdown/issues/313

Related

How to have a horizontally aligned table output in Flextable package in R

Although, there are similar questions posted on the web, my question is specifically related to the shape of the output table which is produced by using the Flextable package in R. More specifically, the following code
library(flextable)
library(tidyverse)
set_flextable_defaults(font.size = 14, theme_fun = theme_vanilla,
background.color = "#EFEFEF", fonts_ignore=TRUE)
flextable(mtcars) %>%
print(preview = "pdf")
produces this pdf output, which is a table vertically aligned. However, I would like to have a horizontally aligned table.
In other words, I want the horizontal page layout, something like the following table. And my question is, how can I get that pdf output, having a horizontal layout, by using the Flextable package in R.

blank cells from apa_tables in papaja knitting to word document with extra spacing

I've been knitting to a Word Document from an .rmd file using papaja. I have found that when there is a blank cell in a row, that particular row's height is disproportionately taller than rows without. I've set up my .rmd using the provided template from papaja.
This table produces a normal looking table in a word document:
data <- mtcars
table_1 <- data %>%
group_by(vs) %>%
summarise("Mean cyl" = mean(cyl), "Mean wt" = mean(wt))
apa_table(table_1, caption = "Table 1 with no blank space")
However, if I remove one of the column headers and replace it with just an empty character string, like this:
table_2 <- table_1
colnames(table_2) <- c("","Mean cyl","Mean wt")
apa_table(table_2, caption = "Table 2 with a blank space")
The row that the blank space is in is much taller than the table without the blank space. I've played around with it and it also happens when I just use kable() to knit a table, so it might have something to do with kable. I'll attach a screenshot of what the two tables look like. Oh, bonus question, is there any way to put "Table X:" and the table caption on the same line? Tables rendered in a word doc
I can confirm that this happens in Word. However, the this doesn't seem to be caused by apa_table() or papaja. If you create a table in pandoc-syntax by hand, you get the same behavior, both with apa6_docx() and the standard word_document()-output format, albeit less pronounced in the latter because of the tighter line spacing.
Table: Table 2 with a blank space
Mean cyl Mean wt
--- --------- ---------
0 7.444444 3.688556
1 4.571429 2.611286
So, this may be unintended behavior in pandoc and you could try opening an issue on GitHub.
As workaround you can use non-breaking space as column header:
colnames(table_2) <- c("\\ ","dsfasdf","Mean wt")
apa_table(table_2, caption = "Table 2 with a blank space")

kable produces malformed reference links within lapply function in blogdown

I am using blogdown to to create a blogpost that has a series of tables. Creating a single table using the kable function works fine. If you do
blogdown::new_site()
blogdown::new_post("test", ext = ".rmd")
A new rmd file will be created within the content/post directory of the project. If you open that file and create a single table by doing
```{r test1}
library(knitr)
library(magrittr)
library(shiny)
data.frame(a= c(1,2,3)) %>% kable(caption = 'test',format = 'html')
```
A correctly formatted table will be generated. The caption will read "
Table 1: test" If you look at the code of the generated site, the caption will look like this.
<caption>
<span id="tab:test1">Table 1: </span>test
</caption>
Ideally I don't have any desire to label the table as Table 1 in the first place but that is another question. If formatting of captions by kable can be disabled entirely, I'd also be happy.
However if I use lapply to generate 2 tables instead
```{r test2}
lapply(1:2,function(x){
data.frame(a= c(1,2,3)) %>% kable(caption = 'test2',format = 'html') %>% HTML()
}) -> tables
tables[[1]]
tables[[2]]
```
The captions will have the prefix \#tab:test2. If you look at the caption of these tables, you'll see
<caption>(\#tab:test2)test2</caption>
The question is, why kable behaves differently when its called from a lapply compared to its behaviour outside? Note that both of these behaviours are different that its behaviour when simply knitting the file as an html_document.
I did some digging into the kable's code and found that the caption link is created by the knitr:::create_label function. Looking into this function, I saw the part that is responsible for the wrong behaviour seen with the multiple tables.
if (isTRUE(opts_knit$get("bookdown.internal.label"))) {
lab1 = "(\\#"
lab2 = ")"
}
I could not find the code, responsible for the "correct" behaviour with the single table but it seems like knitr internal options are responsible.
Ultimately the behaviour that I want is simply
<caption>test</caption>
which is the behaviour when simply knitting an html document. But I am yet to find a way to set the relevant knitr options and why are they different within the same document.
Edit: Further examination suggests that the issue isn't lapply specific. It can be replicated using a for loop or even { by itself. A complete post with all the problematic examples can be acquired from this issue on knitr's github page. This github repo includes the basic blogdown site that replicates the issue
Turns out the responsible party is not the lapply call but the HTML call at the end. It seems like the regular process by knitr in blogdown and bookdown is to have a temporary marker for the table references in the form of (\#tab:label) and replace it with the appropriate syntax later in the processing.
I was using the HTML call to be able to use the tags object in shiny/htmltools to bind the tables together. This approach seems to make the process of replacing the temporary marker impossible for reasons outside my understanding. For my own purposes I was able to remove the temporary marker all together to get rid of both malformed captions and the working-as-intended table numbers by doing
remove_table_numbers = function(table){
old_attributes = attributes(table)
table %<>% as.character() %>% gsub("\\(\\\\#tab:.*?\\)","",.)
attributes(table) = old_attributes
return(table)
}
data.frame(a= c(1,2,3)) %>% kable(caption = 'test',format = 'html') %>% remove_table_numbers
This question still would benefit from a proper explanation of the reference link placement process and if its possible to apply it to tables in HTML calls as well. But for know this solves my issue. I'll gladly switch the accepted answer if a more complete explanation appears

Generating a table in word from rmarkdown using the flextable package error

I have been trying to generate a table in R Markdown with output to word looking like this (a very common table format for chemical sciences):
I started with kable using markdown syntax to get the subscripts etc (eg. [FeBr~2~(dpbz)~2~]) which worked in the word document file. However, i could not modify the table design and most importantly i could not figure out how to get the headings to display properly. So i moved on using the flextable package. Here is my code so far (still work in progress):
```{r DipUVvis,echo=FALSE, anchor='Table S', tab.cap="Summary of catalytic reactions monitored with *in situ* UV-Vis spectroscopy."}
df<-data.frame(Entry=c('AMM 51^*a*^','AMM 52^*a*^','AMM 53^*a*^','AMM 54^*a*^','AMM 57^*b*^','AMM 58^*c*^','AMM 59^*d*^'),
Precat=c('[FeBr~2~(dpbz)~2~] (4.00)','[FeBr~2~(dpbz)~2~] (2.00)','[FeBr~2~(dpbz)~2~] (1.00)','[FeBr~2~(dpbz)~2~] (0.50)','[FeBr~2~(dpbz)~2~] (2.00)','[FeBr(dpbz)~2~] (1.00)','[FeBr~2~(dpbz)~2~] (2.00)'),
Nucl=c('Zn(4-tolyl)~2~/2 MgBr~2~ (100)','Zn(4-tolyl)~2~/2 MgBr~2~ (100)','Zn(4-tolyl)~2~/2 MgBr~2~ (100)','Zn(4-tolyl)~2~/2 MgBr~2~ (100)','Zn(4-tolyl)~2~/2 MgBr~2~ (100)','Zn(4-tolyl)~2~/2 MgBr~2~ (100)','Zn(4-tolyl)~2~/2 MgBr~2~ (100)'),
BnBr=c(0,0,0,0,'42 + 42',42,42))
tbl<-regulartable(df)
tbl<-set_header_labels(tbl,Entry='Entry',Precat='Pre-catalyst (mM)',Nucl='Nucleophile (mM)',BnBr='BnBr (mM)')
tbl <- align( tbl, align = "center", part = "all" )
tbl<-autofit(tbl)
tbl
```
This took care of the headers and with a bit of setting the rest parameters i think i can get the table to look like in the picture above. The resulting table looks fine in the Rstudio console from a formatting perspective:
However, there are two major issues:
1) The subscripts/superscripts are not being translated.
2) When i Knit to word, instead of a table i get 5 pages of code, which from my understanding must be the html code?
After many hours of trying to sort this out, i found that one possible cause is R studio using an old version of pandoc (https://github.com/davidgohel/flextable/issues/34). Indeed that was the case for me so i changed it by moving the new installed files of pandoc in the correct directory (where r studio is looking) and renaming. This must have worked now (see second figure console section). However it didnt change anything. Then i tried adding in my code:
knit_print(tbl)
This keeps giving an error:
Error in knit_print.flextable(tbl) : render_flextable needs to be used as a renderer for a knitr/rmarkdown R code chunk (render by rmarkdown).
Interestingly, when i removed the last line from the r chunk in R studio (tbl) and added the following below the r chunk (not in it):
`r tbl`
The table was generated in word (of course i still didnt get the subscripts and superscripts right). It also had the Figure caption on the top and not the bottom as a desirable side effect of generating the table after the main r chunk.
Any ideas of what is going on and how can i get the correct table output in word? Really confused here, so thank you in advance for your help.
UPDATE: If i remove the anchor = 'Table S' from the chunk header the table comes out ok (still without the subscripts or superscripts though) but then i cant automatically number the tables (i have used this: https://gist.github.com/benmarwick/f3e0cafe668f3d6ff6e5 for autonumbering and cross referencing).

Comments in Rpres

I'm trying to put a comment in my Rpres script, but I don't want that comment to appear in the final presentation. I know that in an R script, the comments are expressed by #comment. But how it would be in Rpres?
For example, for a specific slide:
Title of slide:
```{r}
vector <- c(1,2,4)
dataframe <- data[data$line == 4,]
table <- table(dataframe$line2)
```
I want to add a comment here about a code line (this comment would be visible only for me in my Rpres script, but not on the presentation display).
Then I explain the results (this part would be on the presentation display).
Is there a special key like % or # that would make that work?
There is more than one way of doing this, what I found to be fairly generic is the following format:
[//]: # ("this is just a comment")

Resources