Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Live code that goes with Data Rectangling talk
#' ---
#' output:
#' word_document
#' ---
knitr::opts_chunk$set(collapse = TRUE, comment = "#>")
#+
library(repurrrsive)
library(tidyverse)
## Hello got_chars!
?got_chars
## ick
str(got_chars)
## enjoy the Object Explorer
#View(got_chars)
got_chars[[9]][["name"]]
got_chars[[9]][["titles"]]
## back to slides!
## use special shortcuts for extracting elements
## map(YOUR_LIST, "TEXT")
## map(YOUR_LIST, i)
map(got_chars, "name")
map(got_chars, 3)
## how would you do with lapply? inline an anonymous function
lapply(got_chars, function(x) x[["name"]])
lapply(got_chars, `[[`, 3)
## use map()'s special friends for specifying type
## map_chr(YOUR_LIST, .f, ...)
## map_dbl(YOUR_LIST, .f, ...)
## map_int(YOUR_LIST, .f, ...)
## map_chr(YOUR_LIST, .f, ...)
map_chr(got_chars, "name")
map_lgl(got_chars, "alive")
## how would you do with vapply? inline an anonymous function & provide a mold
vapply(got_chars, function(x) x[["name"]], FUN.VALUE = character(1))
## back to slides!
library(glue)
## use toy example you control
glue_data(
list(name = "jenny", born = "in Atlanta"),
"{name} was born {born}."
)
## specific examples in your data
glue_data(got_chars[[2]], "{name} was born {born}.")
glue_data(got_chars[[9]], "{name} was born {born}.")
## drop YOUR PROVEN-TO-WORK code into map()
map(got_chars, ~ glue_data(.x, "{name} was born {born}."))
## shows the "formula syntax" for .f
## exploit type-specific, simplifying map
map_chr(got_chars, ~ glue_data(.x, "{name} was born {born}."))
## shows the "formula syntax" for .f
## back to slides!
## put a list into a tibble
got <- tibble(
name = map_chr(got_chars, "name"),
stuff = got_chars
)
got
## drop YOUR WORKING map() code into mutate()
got %>%
mutate(b = map_chr(stuff, ~ glue_data(.x, "{name} was born {born}."))) %>%
select(-stuff)
## use your usual data manipulation tools, even in presence of a list
got %>%
mutate(
alive = map_lgl(stuff, "alive"),
titles = map(stuff, "titles"),
n_titles = map_int(titles, length)
) %>%
# count(n_titles) %>%
filter(n_titles > 4, alive) %>%
select(-stuff) %>%
unnest()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.