Here is a code sample that will generate the table that I want in R Markdown:
---
title: "Table"
author: "Nick"
date: "9 June 2017"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(tables)
Age <- sample(0:19, 500, replace = TRUE)
Unborn <- sample(0:1, 500, replace = TRUE)
GenderBand <- sample(1:3, 500, replace = TRUE)
EthnicityGroup <- sample(1:5, 500, replace = TRUE)
InitialCategory <- sample(1:5, 500, replace = TRUE)
data <- data.frame(Age, Unborn, GenderBand, EthnicityGroup, InitialCategory)
Age <- 6
data$Age[data$ChildAge31March == 0] <- 1
data$Age[data$ChildAge31March >= 1 & data$ChildAge31March <= 4] <- 2
data$Age[data$ChildAge31March >= 5 & data$ChildAge31March <= 9] <- 3
data$Age[data$ChildAge31March >= 10 & data$ChildAge31March <= 15] <- 4
data$Age[data$ChildAge31March >= 16 & data$ChildAge31March <= 50] <- 5
data$Age <- factor(data$Age,
levels = c(1,2,3,4,5,6),
labels = c("Under 1",
"1 to 4 Years Old",
"5 to 9 Years Old",
"10 to 15 Years Old",
"16 to 50 Years Old",
"Other"))
data$Unborn <- factor(data$Unborn, levels = c(0,1), labels = c("Born","Unborn"))
data$GenderBand <- factor(data$GenderBand, levels = c(1,2,3), labels = c("Male","Female","Unknown"))
data$EthnicityGroup <- factor(data$EthnicityGroup,
levels = c(1,2,3,4,5,6),
labels = c("White","Mixed","Asian","Black","Other","Refused"))
data$InitialCategory <- factor(data$InitialCategory,
levels = c(1,2,3,4,5),
labels = c("Emotional",
"Multiple",
"Neglect",
"Phyical",
"Sexual"))
Table <- tabular(GenderBand + (Unborn * Age) + EthnicityGroup ~ InitialCategory, data=data)
```
```{r output, echo=FALSE, results="asis"}
html(Table)
```
This works pretty much perfectly how I want it. Giving me this: However when I did this using my real data, I got this: I've identified the issue in the HTML, and it appears that for some reason, on some cells (the broken ones), html(tablular()) has output this:
I'm completely lost as to why it seems to be scrambling the HTML output, as the numbers are generated by R (they're counts of factors).
In theory I could perhaps store the HTML output in a variable and gsub()
the offending strings, but that seems like a messy work around for something that shouldn't really need one. Does anyone have any insight on this?