r knitr kable padding not working with format = "html" - html

I am trying to add padding to a table I am creating in an RMarkdown file that will generate both a pdf and an html flexdashboard. I know that there are a number of functions/packages I could use (pander, xtable, DT, etc.), but I would prefer to use the kable function from the knitr package.
The trouble I am having is that the padding argument does not seem to work. I would appreciate any help in solving this without having to add custom CSS to my document.
As a example, I have tried to run the code with padding set to 0, 10, 20 but the tables all look identical in the html file.
knitr::kable(head(cars), format = "html", padding = 0)
knitr::kable(head(cars), format = "html", padding = 10)
knitr::kable(head(cars), format = "html", padding = 20)
I am using knitr_1.14 and rmarkdown_1.0, and my session information is as follows.
R version 3.3.0 (2016-05-03)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 7 x64 (build 7601) Service Pack 1

The option table.attr='cellpadding="20px"' does not work for me. Using CSS styles and adding a class to the table with table.attr='class="myTable"' leads to all tables having the desired padding property (even if only one table carries the new class).
If I only want to modify one single table I usually go with jQuery:
---
title: "Table Cell Padding"
output: html_document
---
```{r}
knitr::kable(head(cars), format = "html")
```
```{r}
knitr::kable(head(cars), format = "html", table.attr='class="myTable"')
```
<style>
.myTable td {
padding: 40px;
}
</style>
Another option is to use jQuery to edit individual elements. The following example modifies the table in the same way as the CSS styles above.
<script type="text/javascript">
// When the document is fully loaded...
$(document).ready(function() {
// ... select the cells of the table that has the class 'myTable'
// and add the attribute 'padding' with value '20px' to each cell
$('table.myTable td').css('padding','20px');
});
</script>
Here I add the class myTable to the table I want to modify. Afterwards I execute some JavaScript (see comments).
You could add any other CSS property to the table elements (or the table itself $('table.myTable').css(...)) in the same way (e.g. $('table.myTable td').css('background-color','red');)

Related

vue - inserting rows and columns into a table with scoped css

So I'm trying to insert rows and columns into a table using the code below:
add_to_table(type) {
switch (type) {
case "row":
let columns = this.$refs.table.rows[0].cells.length;
let row = this.$refs.table.insertRow(-1);
row.height = "20px";
for (let i = 0; i < columns; i++) {
let cell = row.insertCell(-1);
cell.innerHTML = " ";
}
break;
case "column":
for (let row of this.$refs.table.rows) {
let cell = row.insertCell(-1);
cell.innerHTML = " ";
}
break;
}
}
However, this doesn't seem to maintain the css (doesn't add the data-* stuff to it).
I'm currently working around this by using v-for:
<tr v-for="row in rows">
<td v-for="column in columns">
</td>
</tr>
https://codesandbox.io/s/8n728r5wr8
Your created rows and columns are not getting styled because the <style> you declared is scoped.
For the elements to get the scoped style, they must have a data-v-SOMETHING attribute. The elements you create manually, not via Vue, don't have that attribute.
WARNING: Vue is data-driven, the correct, simplest, more predictable
and maintainable way of achieving what you want is mutating a data
attribute and letting Vue's templates react to it accordingly (using
directives like v-for). Your solution is not optimal. You have been warned.
That being said, you have some options:
Declare an additional <style> (non-scoped) tag along the scoped one. The created elements will pick up these styles. Drawback: the styles will be global. Advantage: you don't depend on Vue internals, you don't have to always add the data-v attribute (see below).
Example:
<style scoped>
...
</style>
<style>
/* EXAMPLE OF GLOBAL STYLE ALONGSIDE A SCOPED ONE */
tr, td {
box-shadow:inset 0px 0px 0px 1px orange;
}
</style>
Get a hold of the data-v-SOMETHING attribute. It is available at this.$options._scopeId. Double Warning: the prefix _ means it is internal code. It may change without notice. Your app may be forever stuck with the current Vue 2.x versions. You have been warned again.
So, whenever you create elements, just add the attribute. Example:
// row example
let row = this.$refs.table.insertRow(-1);
row.setAttribute(this.$options._scopeId, ""); // <== this adds the data-v-XYZ attr
...
// cell example
let cell = row.insertCell(-1);
cell.setAttribute(this.$options._scopeId, ""); // <== this adds the data-v-XYZ attr
Here's a CodeSandbox demo containing examples for both alternatives.

Using R and plot.ly, how to save multiples htmlwidgets to my html?

I´m starting to play with plot.ly in R and I´m amazed with the possibilities to publish my graphs directly in html using htmlwidgets.
Until now I´m unable to save multiple widgets in the same html.
I have saved multiple widgets in stand-alone htmls and than combine it by hand in the html code, but I would like to be able to do it in R.
A simple example:
#graph
graph<- ggplot(df, aes(x = Data, y=tax))+ geom_bar(stat='identity')
gg <- ggplotly(graph)
# save as HtmlWigdet
htmlwidgets::saveWidget(as.widget(gg), "Index.html")
How can I parse multiple ggplotly objects to saveWidgets?
(This is my first question here in stackoverflow, hope I did it right! Regards!)
This is the function I adapted from bits and pieces of the htmltools package to save a tag list and then return an iframe tag. You can wrap multiple htmlwidgets with htmltools::tagList, and then use this function to save the whole bunch.
save_tags <- function (tags, file, selfcontained = F, libdir = "./lib")
{
if (is.null(libdir)) {
libdir <- paste(tools::file_path_sans_ext(basename(file)),
"_files", sep = "")
}
htmltools::save_html(tags, file = file, libdir = libdir)
if (selfcontained) {
if (!htmlwidgets:::pandoc_available()) {
stop("Saving a widget with selfcontained = TRUE requires pandoc. For details see:\n",
"https://github.com/rstudio/rmarkdown/blob/master/PANDOC.md")
}
htmlwidgets:::pandoc_self_contained_html(file, file)
unlink(libdir, recursive = TRUE)
}
return(htmltools::tags$iframe(src= file, height = "400px", width = "100%", style="border:0;"))
}
What is the use-case you're after? You may want to consider adding these graphs to a Flexdashboard (which is created in R Markdown). It's been my recent goto, combined with Plotly.

R tableHTML add_css text-align centre not working in Shiny

I'm trying to style a table in a Shiny app using the tableHTML package in R.
When I use the tableHTML() function in R it produces exactly what I want. I use the add_css_column to align the text in the column to the centre. However when I use it in a Shiny app the headers end up left aligned and the rows centre aligned. Any ideas how I can fix this?
output$viewers_website_top <- renderUI({
tableHTML(website_index, rownames = FALSE, widths=c(200,200)) %>%
add_css_column(css = list("text-align", "center"),
column_names = names(website_index))
})
This is a common issue with bootstrap 3 unfortunately. Whenever you use shiny it loads up a bootstrap 3 css (immediately) which makes it difficult to overwrite.
As for the solution to this using add_css_header would probably solve this one. add_css_header would change the th tag of the HTML table to the one you like (whereas add_css_header would change the td tags below the headers):
output$viewers_website_top <- renderUI({
tableHTML(website_index, rownames = FALSE, widths=c(200,200)) %>%
add_css_header(css = list("text-align", "center"),
headers = 1:ncol(website_index))
})
Another thing you can do is to add a separate css file with shiny::includeCSS. There is more info here and here on how to use includeCSS.
In the css file you need to write:
.table_website_index th {
text-align: center;
}
And that should do it!
P.S. table_website_index is the class the package assigns to the table which you can also change with the class argument.
P.S.2 I am the developer - thanks for using the package :)

self created tables with shiny

I am wondering how I can create a (html) table cell by cell with dynamic content in shiny?
right now I am using the following combination:
server.R
output$desc <- renderTable(
hdx.desc()
)
ui.R
tabsetPanel(
tabPanel("Description", tableOutput("desc"))
)
This works well. I would like to set links to some cells and also add some additional layout setting to the table like bold, without border etc. and also don't want to the row numbers at the front.
How can I do this? I tried the HTML() command, but it did't work.
Thanks for your help.
If you want to use renderTable the easiest way to style your table is using css. Removing the row numbers requires passing the option include.rownames = FALSE to print.xtable. There is a ... argument in the renderTable function that does this. You can include html in your table and use the sanitize.text.function argument.
runApp(list(
ui = bootstrapPage(
tableOutput("myTable")
, tags$head(tags$style(type="text/css",
"#myTable table th td {
border: 1px solid black !important;
}
#myTable table th
{
background-color:green;
color:white;
}"
))
),
server = function(input, output) {
output$myTable <- renderTable({
temp = c(runif(4),
as.character(tags$a(id = 'myId', href='http://www.example.com', runif(1)))
)
data.frame(date=seq.Date(Sys.Date(), by=1, length.out=5), temp = temp)
}, include.rownames = FALSE, sanitize.text.function = function(x) x)
}
))
Alternatively look at renderDataTable which allows you to use http://datatables.net/.
If you know that your table will be static and that only the content will be dynamic, you could follow my approach annotated here: Shiny - populate static HTML table with filtered data based on input
In short, I build a static html table and wrap it in a function in a seperated R file, source it in the server and call it in the renderUI() function with the newly filtered data. Thus, the table content gets updated with the user input.
A future project will be a function that allows the user to generate a static html table in a dynamic way, e.g., a function that creates a table with X rows, Y columns, rownames[], colnames[], etc. If I succeed, I will post my solution here.

How to get cfspreadsheet to render html

I'm trying to create an excel file with cfspreadsheet. In one of the columns I have html code, but for some reason, in the excel file the html doesn't get rendered it's just plain text. eg. <b>blabla</b> instead of being bolded.
Do you know any solutions to this?
The reason is that cfspreadsheet is based on POI which does not support html content.
As user1450455 mentions, you can format whole cells using any of the built in formatting functions such as SpreadsheetFormatCell.
sheet = spreadSheetNew();
spreadSheetFormatCell( sheet, {bold=true} , 1, 1 );
spreadSheetSetCellValue( sheet, "blablah", 1, 1 );
If you are looking to create cells with multiple formats (ie bold some characters but not others) that is only possible using the underlying POI library by creating a RichTextString. So it requires much lower level code.
<cfscript>
sheet = spreadSheetNew();
workbook = sheet.getWorkBook();
helper = workbook.getCreationHelper();
richText = helper.createRichTextString("ColdFusion");
// make first few characters bold ie "Cold"
firstFont = workbook.createFont();
firstFont.setBoldweight( firstFont.BOLDWEIGHT_BOLD );
richText.applyFont( 0, 4, firstFont );
// make next characters red ie "Fusion"
secondFont = workbook.createFont();
secondFont.setColor( secondFont.COLOR_RED );
richText.applyFont( 4, 10, secondFont );
// create cell via CF and apply formats
// note, in POI indexes are base 0
spreadSheetSetCellValue( sheet, "", 2, 1);
cellA2 = workbook.getSheetAt(0).getRow(1).getCell(0);
cellA2.setCellValue( richText );
</cfscript>
You can use the spreadsheet formatting functions like SpreadsheetFormatRow or SpreadsheetFormatrows or SpreadsheetFormatColumns.