Skip to content

Instantly share code, notes, and snippets.

@expersso
Created September 7, 2017 13:09
Show Gist options
  • Save expersso/ddaacfeb2683429cbe9612f4c9219b5f to your computer and use it in GitHub Desktop.
Save expersso/ddaacfeb2683429cbe9612f4c9219b5f to your computer and use it in GitHub Desktop.
Unnesting lists with dplyr
# Motivation: https://twitter.com/zentree/status/905666552925536256
library(tidyverse)
library(rlang)
unnest_dfc <- function(df, var) {
var <- enquo(var)
new_df <- df %>%
pull(!!var) %>%
transpose() %>%
map(unlist) %>%
as_tibble()
cbind(select(df, -!!var), new_df)
}
describe <- function(x) {
mn <- mean(x, na.rm = TRUE)
dev <- sd(x, na.rm = TRUE)
n <- sum(!is.na(x))
cv <- dev/mn*100
list("mean" = mn, "dev" = dev, "n" = n, "cv" = cv)
}
## IO
"http://www.quantumforest.com/wp-content/uploads/2017/09/field_data.csv" %>%
read_csv() %>%
group_by(family) %>%
summarise(model = list(describe(stem))) %>%
unnest_dfc(model) %>%
str()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment