Created
February 4, 2022 04:26
-
-
Save dblodgett-usgs/051eb7732a816f2e6064404533ff6393 to your computer and use it in GitHub Desktop.
unnest a data.frame in base R
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#' 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 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I created this because of all the churn I've had in my use of tidyr::unnest. Hope it helps someone.