Last active
December 23, 2015 15:19
-
-
Save lcolladotor/6654729 to your computer and use it in GitHub Desktop.
Example on how to fix dTable() when Inf and -Inf values are present. Includes .Rprofile for using knitrBootstrap via RStudio
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
## For knitr bootstrap | |
## More info at http://www.rstudio.com/ide/docs/authoring/markdown_custom_rendering | |
options(rstudio.markdownToHTML = | |
function(inputFile, outputFile) { | |
library(knitrBootstrap) | |
knit_bootstrap_md(input=inputFile, output=outputFile, code_style="Brown Paper", chooser=c("boot", "code"), show_code=FALSE) | |
} | |
) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Infinite values in dTable() | |
========================== | |
This short example shows how having Inf and -Inf values can break up the `dTable()` function in `rCharts`. The fix is simple: replace those values by some other large/small number respecitvely. | |
```{r setup} | |
library(data.table) | |
library(rCharts) | |
library(knitr) | |
render_html() | |
``` | |
# Error | |
<link rel="stylesheet" href="http://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.4/css/jquery.dataTables.css" /> | |
<script src="http://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.4/jquery.dataTables.min.js"></script> | |
The following table does not because Inf and -Inf are not recognized by DataTables as shown in the browser console. | |
```{r, results="asis"} | |
data <- data.frame(x=c(-Inf, Inf, 3, 4), y=letters[1:4]) | |
t1 <- dTable(data.table(data), sPaginationType="full_numbers", iDisplayLength=100, sScrollX="100%") | |
t1$print("error", cdn=TRUE) | |
``` | |
# Fix | |
The following function takes a data.frame and for the columns of interest it replaces the Inf and -Inf values by 1e100 and -1e100 respectively. The colsubset argument can be useful if your data.frame has columns that are not numeric. | |
```{r replaceInf} | |
replaceInf <- function(df, colsubset=seq_len(ncol(df))) { | |
for(i in colsubset) { | |
inf.idx <- !is.finite(df[, i]) | |
if(any(inf.idx)) { | |
inf.sign <- sign(df[inf.idx, i]) | |
df[inf.idx, i] <- inf.sign * 1e100 | |
} | |
} | |
return(df) | |
} | |
data2 <- replaceInf(data) | |
``` | |
# Fixed =) | |
Now the table is displayed =) | |
```{r, results="asis"} | |
t2 <- dTable(data.table(data2), sPaginationType="full_numbers", iDisplayLength=100, sScrollX="100%") | |
t2$print("fixed", cdn=TRUE) | |
``` | |
# Reproducibility | |
```{r session} | |
sessionInfo() | |
``` | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment