Not able to format dataframe using xtable - r-markdown

I have a dataframe and I want to display that into a R markdown HTML file. I am able to generate a table using Kable function of Knitr, but I wanted to change look and feel, like highlighting the header. as some suggested on Stackoverflow to use xtable, I tried to do that. I took reference from Stackoverflow and try to design my outlike like this.
large <- function(x){
paste0('{\\Large{\\bfseries ', x, '}}')
}
italic <- function(x){
paste0('{\\emph{ ', x, '}}')
}
dat <- Final_Summary_table[1:3, 1:6]
print(xtable(dat),
sanitize.rownames.function = italic,
sanitize.colnames.function = large,
booktabs = TRUE,
floating = TRUE)
But instead of getting a beautiful table, what I am getting is something like we writee on a notepad.
% latex table generated in R 3.3.1 by xtable 1.8-2 package % Mon Nov 14 09:33:01 2016 \begin{table}[ht] \centering \begin{tabular}{rllrrrl} \toprule & {\Large{\bfseries ODS_Tables}} & {\Large{\bfseries AppDS_Tables}} & {\Large{\bfseries ODS_Total_Records}} & {\Large{\bfseries AppDS_Total_Records}} & {\Large{\bfseries Change_in_Count}} & {\Large{\bfseries Results}} \\ \midrule {\emph{ 1}} & HCC & tRefHCCCodes & 338.00 & 338.00 & 0.00 & PASS \\ {\emph{ 2}} & HCC\_COEFF & tRefHHCCOEFFs & 1166.00 & 794.00 & 372.00 & FAIL \\ {\emph{ 3}} & HCC\_HIERARCHY & tRefHHCHierarchies & 337.00 & 253.00 & 84.00 & FAIL \\ \bottomrule \end{tabular} \end{table}
any clue or help please.

I used follwing CSS formatting and it solved the issue.
<STYLE TYPE="text/css">
<!--
table {
width:100%;
}
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}
th, td {
padding: 5px;
text-align: left;
}
table tr:nth-child(even) {
background-color: #eee;
}
table tr:nth-child(odd) {
background-color:#fff;
}
table th {
background-color: black;
color: white;
}
--->
</STYLE>

Related

Is there a method to pass the formatting selection made in the PowerBI menu to a Deneb visual?

See title, trying to pass a formatting selection (for example, percentage) to a Deneb visual instead of defining it in the vega / vega-lite JSON, and wanted to know if such a thing was possible.
Right now, we are just manually changing the formatting in the JSON
No, but Kerry Kolosko has a clever solution for this in her KPI charts that are in the sample file for the Deneb visual. In addition to passing in number fields, she also does formatting in DAX and passes in text to use with text marks.
DAX
Format Variance =
var a = calculate(DIVIDE(MAX('KPIsDATA'[Actual]),'KPITarget'[KPITarget Value])-1,'KPIsDATA'[Date]=MAX('KPIsDATA'[Date]))
var b = FORMAT(ABS(a),"#%")
Var c = IF(a>0,"▲ " , "▼ ")
Var d = IF(a>0," above target" , " below target")
Return
c & b & d
You could do an "Auto" format like this in DAX:
Format Actual =
VAR _number = SUM(KPIsDATA[Actual])
VAR _digits = 1
RETURN IF( ABS(_number) >= 1000000000, FORMAT(_number, "0,,," & IF(_digits > 0, ".", "") & REPT("0",_digits) & "B"),
IF( ABS(_number) >= 1000000, FORMAT(_number, "0,," & IF(_digits > 0, ".", "") & REPT("0",_digits) & "M"),
IF( ABS(_number) >= 1000, FORMAT(_number, "0," & IF(_digits > 0, ".", "") & REPT("0",_digits) & "K"),
FORMAT(_number, "0" & IF(_digits > 0, ".", "") & REPT("0",_digits) )
)
)
)

How to knit out table codes into table in R markdown

I am a basic-level learner of R. I am having a problem knitting out tables with a code my professor designed for the students. The code for table designs is set as below. I put this in my R markdown as below.
```{r, results="hide", message=FALSE, warning = FALSE, error = FALSE}
## my style latex summary of regression
jhp_report <- function(...){
output <- capture.output(stargazer(..., omit.stat=c("f", "ser")))
# The first three lines are the ones we want to remove...
output <- output[4:length(output)]
# cat out the results - this is essentially just what stargazer does too
cat(paste(output, collapse = "\n"), "\n")
}
```
After this, I tried printing this out with knitr.
```{r, message=FALSE, warning = FALSE, error = FALSE}
set.seed(1973)
N <- 100
x <- runif(N, 6, 20)
D <- rbinom(N, 1, .5)
t <- 1 + 0.5*x - .4*D + rnorm(N)
df.lm <- data.frame(y = y, x =x, D =D)
df.lm$D <- factor(df.lm$D, labels = c('Male', 'Female'))
##REGRESSION
reg.parallel <- lm(y ~ x + D, data = df.lm)
jhp_report(reg.parallel, title = "Result", label = "tab:D", dep.var.labels = "$y$")
```
As a result, instead of a table, it keeps on showing only the pure codes. I would like to know how I have to set up R markdown for it to print out the table instead of the codes. This is how the result looks like when I knit it.
I expected that there must be some setup options to print the table out. But I couldn't find the right one. Also, my assignment for class requires students to use this code. I did find other options like knitr::kable but I would like to use the given code for this assignment.
Thank you in advance!

Ocaml : This expression has type int but an expression was expected of type int ref [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 months ago.
Improve this question
Having this code:
type player = Orange | Red | Blue | White ;;
type piece =
Knight of player
| Town of player
| City of player
| Road of player
| Wool of player
| Brick of player
| Lumber of player
| Grain of player
| Ore of player ;;
let posessions =
[| Ore Orange; Road Red; Ore Blue; Ore White;
Lumber White; Ore Red; Knight Red; Road Orange;
Lumber Red; Brick Red; City White; Lumber White;
Wool Red; City White; Ore White; Brick White;
Road Blue; Lumber Blue; Grain Orange; Wool Red;
Road White; Knight White; Grain White; Wool Orange;
City Blue; Ore Orange; Knight Orange; Brick White;
Ore Red; Ore White; Road Orange; Knight Red;
Lumber Orange; Wool Orange; City Orange; Wool Blue;
Lumber White; City Red; Grain Red; Lumber Red;
Ore White; Grain White; Brick Orange; Brick White;
Road Blue; Grain Red; Ore White; City White;
Road White; Knight Orange; Brick Red; Ore White;
Lumber Orange; Ore Blue; Road Blue; Brick White;
Brick Orange; Ore Orange; Ore Blue; Ore Orange;
Ore Orange; Brick Orange; Brick White; Road Orange;
Lumber White; Knight Red; Brick White; Brick Orange;
Road Blue; Brick Orange; Lumber Blue; Road Blue;
Ore Red; Grain Blue; Wool Red; Town Red; Ore Orange;
Lumber White; Road Red; Road Blue; Town Blue;
Wool Red; Lumber Blue; Wool Blue; Town Red;
Grain Orange; Brick Blue; Knight Red; Wool White;
Ore Orange; Ore Blue; Lumber White; Wool White;
Brick Orange; Ore Blue; Grain Red; Wool Blue;
Road Red; Ore Blue; Lumber Orange |];;
let if_orange array =
let counter = ref 0
and roadcounter = ref 0
and knightcounter = ref 0
and n = Array.length array in
for i = 0 to n - 1 do
let a = Array.get array i in
(if a = (Town Orange) then counter := !counter + 1
else if a = (City Orange) then counter := !counter + 2
else if a = (Road Orange) then roadcounter := !roadcounter + 1
else if a = (Knight Orange) then knightcounter := !knightcounter + 1
else counter := !counter + 0)
done ;
(if roadcounter >= 5 then counter := !counter + 2
else counter := !counter + 0)
(if knightcounter >= !3 then counter := !counter + 2
else counter := !counter + 0 );
!counter;;
In for loop, I just wanted to add up some values to counter if the statements are valid. After it, I wanted to save the values for the counter, roadcounter and knightcounter. Then, in least to last if statement, increase the value of counter if roadcounter >= 5 (and save counter) and similarly for the knightcounter. However, I'm getting an error after I compile.
Error: This expression has type int but an expression was expected of type int ref
Am I supposed to int ref number 5 for comparison? Or did I somehow misplace the () or ;;?
Your problem is in this line:
if roadcounter >= 5 then
Indeed, roadcounter is an int ref, but you're comparing it to an int. You need ! before roadcounter.
There is a similar error a few lines later.
Update
Thanks for adding the types. However, they are not well formed. The definition of type piece stops abruptly in the middle of the keyword of.

Table in Bookdown/Huskydown with several features (Citation, Caption, URL, PNG Figure, ...)

I would like to include a table in an R markdown document (Bookdown/Huskydown) which should meet the following requirements. Ideally, the table works with several output formats, e.g. LaTex/PDF and HTML.
Requirements:
Table width: fixed
Cell width: fixed
Vertical alignment: cell content aligned to the top
Text formatting: like bold or italics (best would be if md formatting supported, such that code is output agnostic) and allow for line breaks in longer texts
Citations: should be rendered
URLs: as clickable links both in HTML and LaTex/PDF
Figures: include
figures stored locally, either in
a markdown way ![](Rlogo.png) or
a knitr way knitr::include_graphics("Rlogo.png")
figures taken straight from the web
Caption for the table
Captions text formatting: caption should also allow for text formatting
Footnote: include footnotes in the table
Table numeration: tables are should be numerated
Referencing the table: in the document is needed
Notes regarding different approaches
Fixed cell width: in markdown the number of "-"s in table header determine cell width
Linebreaks:
LaTex:\\linebreak
All others: <br/>
Referencing
LaTex: add \label{foo} => \ref{foo} ( \#ref(foo))
Markdown: add Table: (\#tab:md-table) Caption==> \#ref(tab:md-table))
Comments on different approaches
Markdown: easy coding of tables in markdown
Kable & kableExtra: Versatile R markdown coding of the table, but vertical text alignment obscure and figures are not included in PDF
Pander: achieves the most, but no vertical alignment and footnotes
Huxtable: most promising, but figures are not included in PDF
This is less an answer than providing MWEs for the table shown above
```{r}
# create some random text
library(stringi)
some_text <- stri_rand_lipsum(1)
some_text <- substr(some_text, 1, 75)
# create dataframe with some stuff
figpath <- "figure/"
df <- data.frame(
Citation = c("#R-base", "#R-bookdown"),
Textfield = c("**Formatted** string<br/> -- _Everyone_ needs H^2^O", some_text),
URL = c("[R-url](https://www.r-project.org/)", "[bookdown](https://bookdown.org/)"),
fig_local_md = c(
paste0("![](", figpath, "Rlogo.png){ width=10% height=5% }"),
paste0("![](", figpath, "bookdownlogo.png){ height='36px' width='36px' }")
)#,
# not working:
# fig_local_knitr = c("knitr::include_graphics('figure/Rlogo.png')", "knitr::include_graphics('figure/bookdownlogo.png')")
)
# only include if output format is HTML, else pander throws error
if (knitr::is_html_output()) {
df$fig_web <- c("![](https://www.picgifs.com/glitter-gifs/a/arrows/picgifs-arrows-110130.gif)")
output_format <- "html"
}
if (knitr::is_latex_output()) {
output_format <- "latex"
}
```
markdown
Table: markdown table: markdown styling works in HTML (*italics*, **bold**), LaTex styling in PDF (\\textbf{bold})
| Image | Description |
| :--------------------------------------------------------- | :----------------------------------------------------------- |
| ![](figure/Rlogo.png){ width=10% height=5% } | **Image description** [#R-base] <br/>Lorem ipsum dolor sit amet, ... [R-url](https://www.r-project.org/) |
| ![](figure/bookdownlogo.png){ height='36px' width='36px' } | **Image description** [#R-bookdown] <br/>Lorem ipsum dolor sit amet, ... [bookdown](https://bookdown.org/) |
kable table
```{r kable-table, echo=FALSE, out.width='90%', fig.align = "center", results='asis'}
library(knitr)
kable(df,
caption = "kable table: markdown styling works in HTML (*italics*, **bold**), LaTex styling in PDF (\\textbf{bold})",
caption.short = "md styling works in HTML (*italics*, **bold**), LaTex styling in PDF (\\textbf{bold})"
)
```
kableExtra table
```{r kableExtra-table, echo=FALSE, out.width='90%', fig.align = "center", results='asis'}
library(kableExtra)
# http://haozhu233.github.io/kableExtra/awesome_table_in_pdf.pdf
kable(
df,
caption = "kableExtra table: markdown styling works in HTML (*italics*, **bold**), LaTex styling in PDF (\\textbf{bold})",
output_format, booktabs = T, # output_format = latex, html (specify above)
# align = "l",
valign = "top"
) %>%
kable_styling(full_width = F,
latex_options = c(#"striped",
"hold_position", # stop table floating
"repeat_header") # for long tables
) %>%
column_spec(1, bold = T, border_right = T, width = "30em") %>%
column_spec(2, width = "50em") %>%
column_spec(3, width = "5em") %>%
column_spec(4, width = "10em") %>%
column_spec(5, width = "10em") %>%
footnote(general = "Here is a general comments of the table. ",
number = c("Footnote 1; ", "Footnote 2; "),
alphabet = c("Footnote A; ", "Footnote B; "),
symbol = c("Footnote Symbol 1; ", "Footnote Symbol 2"),
general_title = "General: ", number_title = "Type I: ",
alphabet_title = "Type II: ", symbol_title = "Type III: ",
footnote_as_chunk = T, title_format = c("italic", "underline")
)
```
pander table
```{r pander-table, echo=FALSE, out.width='90%', fig.align = "center", results='asis'}
library(pander)
# https://cran.r-project.org/web/packages/pander/vignettes/pandoc_table.html
pander(
df,
caption = "pander table: markdown styling works in HTML and PDF (*italics*, **bold**), LaTex styling in PDF (\\textbf{bold})",
# style = "multiline", # simple
split.table = Inf, # default = 80 characters; Inf = turn off table splitting
split.cells = c(15, 50, 5, 5, 5), # default = 30
# split.cells = c("25%", "50%", "5%", "10%", "10%"), # no difference
justify = "left"
)
```
huxtable table
```{r huxtable-table, echo=FALSE, out.width='90%', fig.align = "center", results='asis'}
library(dplyr)
library(huxtable)
# https://hughjonesd.github.io/huxtable/
hux <- as_hux(df) %>%
# huxtable::add_rownames(colname = '') %>%
huxtable::add_colnames() %>%
set_top_border(1, everywhere, 1) %>%
set_bottom_border(1, everywhere, 1) %>%
set_bottom_border(final(), everywhere, 1) %>%
set_bold(1, everywhere, TRUE) %>% # bold headlines
set_italic(-1, 1, TRUE) %>% # italics in first column (except the first row)
set_valign("top") %>%
set_width(1) %>%
set_col_width(c(0.10,0.45,0.05,0.10,0.10)) %>%
set_wrap(TRUE) %>%
set_position('left') %>% # fix table alignment (default is center)
add_footnote("Sample Footnote") %>%
set_font_size(4)
table_caption <- 'huxtable table: markdown styling works in HTML (*italics*, **bold**), LaTex styling in PDF (\\textbf{bold})'
# Print table conditional on output type
if (knitr::is_html_output()) {
caption(hux) <- paste0('(#tab:huxtable-table-explicit) ', table_caption)
print_html(hux) # output table html friendly (requires in chunk options "results='asis'")
}
if (knitr::is_latex_output()) {
caption(hux) <- paste0('(\\#tab:huxtable-table-explicit) ', table_caption)
hux # if using chunk option "results='asis'" simply output the table with "hux", i.e. do not use print_latex(hux)
}
```
Referencing the tables
works differently for different table types
Adding a short caption for the LoT
Finally adding a short caption for the table of figures is not really working as desired
(ref:huxtable-table-caption) huxtable-table caption
(ref:huxtable-table-scaption) huxtable-table short caption
```{r huxtable-table, echo=FALSE, out.width='90%', fig.align = "center", fig.cap='(ref:huxtable-table-caption)', fig.scap='(ref:huxtable-table-scaption)', results='asis'}
...
```

cleaning txt file in R

I found the following script from asdfree on taxonomies. The current script merges all specialties into a single column asdfree original script. The issue is that the current script ignores the hierarchy of the specialties.
The following code gives you an idea of how there are really multiple levels
library(downloader)
tf <- tempfile()
download("https://raw.githubusercontent.com/ajdamico/asdfree/master/National%20Plan%20and%20Provider%20Enumeration%20System/taxonomy%20id%20table.txt", tf)
z <- readLines(tf)
hmt <- gregexpr("\t", z)
l <- unlist(lapply(hmt, function(x) length(x[x > 0])))
specialty_groups <- pre[l == 1]
specialty_individual <- pre[l == 2]
The issue is that Allegery and Immunology (in first row) is misplaced, and it should really go to the last column.
6 2 Allergy & Immunology 207K00000X Allopathic & Osteopathic Physicians <NA>
7 3 Allergy 207KA0200X Allopathic & Osteopathic Physicians Allergy & Immunology
8 3 Clinical & Laboratory Immunology 207KI0005X Allopathic & Osteopathic Physicians Allergy & Immunology
9 2 Anesthesiology 207L00000X Allopathic & Osteopathic Physicians <NA>
In other words, the data should really look something like this
LEVEL_1 LEVEL_2 LEVEL_3 TAXONOMY
Allopathic & Osteopathic Physicians Allergy & Immunology 207K00000X
Allopathic & Osteopathic Physicians Allergy & Immunology Allergy 207KA0200X
Allopathic & Osteopathic Physicians Allergy & Immunology Clinical & Laboratory Immunology 207KI0005X
How can I achieve this with regex in R?