Skip to content

Instantly share code, notes, and snippets.

@dblodgett-usgs
Created February 4, 2022 04:26
Show Gist options
  • Save dblodgett-usgs/051eb7732a816f2e6064404533ff6393 to your computer and use it in GitHub Desktop.
Save dblodgett-usgs/051eb7732a816f2e6064404533ff6393 to your computer and use it in GitHub Desktop.
unnest a data.frame in base R
#' Unnest a data.frame with one list column
#' @description Will unnest a data.frame that has one list column such that each element
#' of each list has its own row and all other observations are repeated.
#' @param x data.frame
#' @param col character pointing to the list column
unnest <- function(x, col = "set") {
times <- lengths(x[[col]])
base_names <- names(x)[!names(x) == col]
out <- as.data.frame(cbind(sapply(base_names, function(n) rep(x[[n]], times = times))))
names(out) <- base_names
out[[col]] <- unlist(x[[col]])
out
}
@dblodgett-usgs
Copy link
Author

I created this because of all the churn I've had in my use of tidyr::unnest. Hope it helps someone.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment