Skip to content

Instantly share code, notes, and snippets.

@ismayc
Last active March 28, 2016 04:27
Show Gist options
  • Save ismayc/5f9ef3ce857c98938284 to your computer and use it in GitHub Desktop.
Save ismayc/5f9ef3ce857c98938284 to your computer and use it in GitHub Desktop.
A way to use `dplyr`'s `join` functions to extract data from a lookup table
---
title: "Lookup Tables"
output:
html_document:
toc: true
toc_float: true
---
```{r setup, include=FALSE}
pkg <- c("dplyr", "DT")
new.pkg <- pkg[!(pkg %in% installed.packages())]
if (length(new.pkg)) {
install.packages(new.pkg, repos = "http://cran.rstudio.com")
}
lapply(pkg, library, character.only = TRUE)
```
```{r}
set.seed(1) # for reproducible example
n <- 100
groups <- c("V", "W", "X", "Y")
colors <- c("green", "red", "blue", "black")
sizes <- c("small", "medium", "large")
df <- data_frame(
group = sample(groups, size = n, replace = TRUE),
color = sample(colors, size = n, replace = TRUE),
size = sample(sizes, size = n, replace = TRUE)
)
lookup_table <- data.frame(
expand.grid(groups, colors, sizes, stringsAsFactors = FALSE)
)
lookup_table <- lookup_table %>%
rename(group = Var1, color = Var2, size = Var3) %>%
mutate(value = sample(1:nrow(lookup_table), size = nrow(lookup_table), replace = FALSE))
merged <- inner_join(df, lookup_table, by = c("group", "color", "size"))
```
```{r output_table}
datatable(df)
datatable(lookup_table)
datatable(merged)
```
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment