---
title: "Lab - Table One"
author: "J. Lucas McKay"
date: "2025-03-05"
output: html_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = T, collapse = T, warning = F, message = F)
```


***
#### Table 1

```{r}
library(tidyverse)
demo = read_csv("https://jlucasmckay.bmi.emory.edu/global/bmi510/Labs/demographics.csv")

# let's add some random variables to make this a little richer
demo$bmi = rnorm(nrow(demo),18,2)

# filter out icd, and calculate table 1
d1 = demo |> select(-icd)

# table 1 is a data.frame object, very similar to a tibble.
t1 = arsenal::tableby(group~.,data = d1) |> summary() |> as.data.frame()

```

#### Display `data.frame` as `kable`

```{r}
t1 |> knitr::kable()
```

#### Write table data to file for inclusion in report

```{r}
t1 |> write.csv("t1.csv")
```

#### Use `'asis'` output option rather than `kable`

```{r, results='asis'}
arsenal::tableby(group~.,data = d1) |> summary()
```

#### Reformat names

```{r, results='asis'}
# note what str_to_title (as opposed to str_to_title()) represents: a function, not a call to a function
arsenal::tableby(Group~.,data = d1 |> rename_with(str_to_title)) |> summary()
```


#### Modify arguments to get rid of superfluous significant digits

```{r}
t2 = arsenal::tableby(group~.,data = d1) |> summary(digits = 1, digits.p = 2) |> as.data.frame()
t2 |> knitr::kable()
```

#### Modify variable names programmatically 

```{r}
d2 = d1 |> rename_with(stringr::str_to_title)
t2 = arsenal::tableby(Group~.,data = d2) |> summary(digits = 1, digits.p = 2) |> as.data.frame()
t2 |> knitr::kable()
```

#### Sort biomarkers from most to least statistically-significant

```{r}
csf = read_csv("https://jlucasmckay.bmi.emory.edu/global/bmi510/Labs/csf.csv") 
t3 = arsenal::tableby(Group~.,data=csf) |> sort() |> summary() |> as.data.frame()
t3 |> knitr::kable()
```

#### Exclude columns as needed, format

```{r}
dim(t2)

t2 = t2[,-c(5,6)]
t2[t2 == "**Bmi**"] = "**BMI**"
t2[,1] = stringr::str_replace_all(t2[,1],fixed("&nbsp;"),"")
t2[,1] = stringr::str_replace_all(t2[,1],fixed("**"),"")
t2 |> knitr::kable() |> kableExtra::kable_styling(full_width = F)
t2 |> write.csv("t2.csv",na="",row.names=F)

```


#### `DT` tables

##### Example One

```{r}
DT::datatable(d1, class = 'cell-border stripe', selection = 'multiple', editable = 'cell', caption = 'Table 1: This is a simple caption for the table.')
```

##### Example Two

```{r}
DT::datatable(head(iris), editable = list(
  target = 'row', disable = list(columns = c(1, 3, 4))
))
```

##### Example Three

```{r}
DT::datatable(head(mtcars))
```




