I just found out the awesome knitr library in R, when viewing the result in the viewer it seems nice. However, when I write this to a html file the style is lost.
Code
library(knitr)
library(kableExtra)
some.table <-
data.frame (
x = rep(1,3),
y = rep(1,3)
)
some.table
x <- kable(some.table, format = "html") %>%
kable_styling(bootstrap_options = "striped", full_width = F, position = "left")
x
file <- file('test.html')
write(x, file)
Table in viewer
Table in browser
How can I export the table with the same style to a html file?
Note that I have more data in the html file, so I should be able to append it.
Response to comment(s)
User: #Hao
When I use 'inspect element' in the Rstudio viewer, I can find this link to a stylesheet:
However the code herein seems to be huge as it is 582.298 characters.
The typical way of doing this is to put the code inside a rmarkdown document. It will handle everything for you.
The only case you need to use the save_kable function kableExtra is that you have lots of tables and you want to save them as fragments. In that case, you can use
library(kableExtra)
cars %>%
kable() %>%
kable_styling() %>%
save_kable()
Related
When I run the following code manually, in my Rmd file, I end up with a (correct) colored table:
color_table <- c("darkgoldenrod2","darkslategray3", "darkseagreen3", "lightpink2")
job <- c("job1", "job2", "job3","job4")
prof_table <- data.frame(job) %>%
gt()
for (i in 1:length(color_table)) {
prof_table <- tab_style(
data=prof_table,
style = list(
cell_fill(color = color_table[i])),
locations = cells_body(columns = 1, rows = i)
)
}
prof_table
However when i knit it, the colors are gone. I am guessing that this might have to do with the knit going to PDF and the table being HTML. But I am not sure, and not aware of a fix. Does anyone have a solution for me?
This is a known limitation, as the documentation states that tab_style() will only work for HTML output. Here is the relevant excerpt:
At present this function is focused on the application of styles for HTML output only (as such, other output formats will ignore all tab_style() calls).
I am using the huxtable package to create tables in a PDF rendered in bookdown. The table is formatted exactly the way I want it, up until I run the print_md command, after which a border is moved up row from underneath the column names to underneath the header. Also, the header is moved from a centered position to right-aligned. Check it out:
df <- data.frame(
"colname1" = c("something indicator"),
"colname2" = "[Something](http://www.overleaf.com)",
"colname3" = "[Something again](http://www.overleaf.com)")
df <- df %>%
as_hux() %>%
theme_basic() %>%
set_tb_padding(2)
df <- df %>%
set_contents(1, 2:3, c("colname2", "colname3")) %>%
insert_row("", "Header", "Header", after = 0) %>%
merge_cells(1, 2:3) %>%
set_align(1, everywhere, "center") %>%
set_tb_padding(1, everywhere, 0) %>%
set_bold(1, everywhere)
df
Which gives:
Table is formatted correctly. But. You'll notice that the URLs are not formatted correctly. It should only be showing the part within the brackets, which when clicked will take you to the site in parentheses.
This can be remedied with the following code:
df %>% print_md()
Which gives:
Now the URLs look like they should, but the border has erroneously moved up a row, and "Header" is now right-aligned instead of center-aligned. How do I stop that from happening?
Don't ask me why it works. But changing print_md() to set_markdown() fixed both the border and alignment problems.
EDIT: I'm adding #dash2's comment to this answer.
The reason print_md() was causing problems is because it converts the table to markdown format, which R Markdown then reads and produces a table from. So some features (alignment) get lost in translation. It'd be better to print the table in the intended output format, be it Latex, HTML or whatever you're using, instead of markdown.
But the cells with markdown hyperlinks need to be respected still - print_md() is just the wrong way to go about it. Instead, use set_markdown(). This will ensure that, within huxtable itself, cells with markdown code are interpreted as markdown before the table is printed. The printed table will then retain the intended format.
Thank you #dash2 for creating such a powerful package!
Is there a way to export or knit a table directly to word-format in an R-script (instead of R-markdown)? knitr and kableExtra seem to provide a wide range of options to save tables, yet there is no option to export tables as actual word files.
library(tidyverse)
library(kableExtra)
dt <- mtcars[1:5, 1:6]
kbl(dt, caption="Table") %>%
kable_classic(full_width = F, html_font = "Cambria")
save_kable("my_latex_table.png") # alternatives: .jpg and .pdf, but not .doc
Since packages and functions such as htmlreg::texreg() allow you to write the output of statistical models into nicely formatted tables which you can then directly include into word documents, I would imagine that this should also be possible with simple tables (e.g. descriptive statistics). The thing is that I would like to export them directly in the format of a word table instead of an image.
I have a flextable object called html_table which I want to directly put in a word document, in horizontal layout with narrow margins.
I face 2 problems:
1) The approach suggested in the vignette produces extra pages (one before, one after the table). I think this is a known issue but not clear how to solve it.
2) I would like to have narrow margins and the resulting table on horizontal pages to be automatically fitted to the page. I want this so that I can print the table using as much page as I can. My current approach is to manually open the document, change the layout and select "autofit" on Word.
Here's the code I'm using to produce the document. For illustrative purposes, I will use mtcars for my table, but the real one has more rows than mtcars.
html_table <- regulartable(mtcars)
doc <- read_docx() %>%
# Make it landscape
body_end_section_continuous() %>%
# Add the table
body_add_flextable(value = html_table,
split = TRUE
) %>%
body_end_section_landscape()
# Write the .docx
print( doc, target = "my_table.docx" )
In Word document, sections are only defined when they stop (I can not explain why it has been made that way but this is how the underlying xml is...). Also a landscape oriented section need a page break if the preceding section is not landscape oriented.
To autofit a flextable, use function autofit.
library(flextable)
library(officer)
library(magrittr)
html_table <- regulartable(mtcars) %>%
autofit()
doc <- read_docx() %>%
body_add_flextable(value = html_table, split = TRUE) %>%
body_end_section_landscape() %>% # a landscape section is ending here
print( target = "my_table.docx" )
If you don't want extra page, you will need a template with a default page orientation as landscape. Also, you would not need any code to manage orientation nor margins.
I'm just starting with Blogdown and am running into an issue. I wrote a post where I've read a .CSV file and then generated a Kable table from its contents. No sweat. However, when I build the site that CSV file is copied to "public/post/data". I do not want that file to be made available to the public since it contains proprietary information (the columns I've pulled for this table are public info, but other columns are not). I do not think that the CSV file is needed on the public webpage once it is built, but I cannot find a way to not upload it.
I've tried putting the .CSV file in different locations (the "resources" folder and another folder I created named "data_files"). I added .CSV to the ignoreFiles param in config.toml: ignoreFiles = ["\.Rmd$", "\.Rmarkdown$", "_files$", "_cache$", "\.csv$"] Nothing, though, seems to help.
Is there some way to use a .CSV file to generate a table, ggplot, etc. without having that file uploaded to the public website?
Here's the code chunk where I read the CSV file in case that will help.
```{r peerList, echo=FALSE, results='asis'}
dataloc <- here("resources","peers.csv")
df <- read.csv(dataloc)
names <- select(df,Name,City,State,County,Zip) %>%
mutate(Zip = str_sub(Zip,1,5)) %>% # change the 9-digit zips to 5
mutate(County = str_replace(County,"County","")) %>% # del the word 'county'
arrange(State,Name)
kable(names, "html") %>%
kable_styling(bootstrap_options = "striped",
full_width = F,
position = "center"
)
```