Skip to content

Instantly share code, notes, and snippets.

@luisDVA
Created June 26, 2017 22:28
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save luisDVA/0a479881450181f06ac5a117a6aa5d46 to your computer and use it in GitHub Desktop.
Save luisDVA/0a479881450181f06ac5a117a6aa5d46 to your computer and use it in GitHub Desktop.
function to untangle header rows from a variable
## UNTANGLE FUNCTION
# Luis D. Verde (www.liomys.mx)
#' Pull interspersed header data into own column
#'
#' @param dframe The tibble or data frame with the interspersed headers in the first column
#' @param matchstring the string to match to pull the header rows (quoted character)
#' @param newCol name for the new variable that will be added to the df (quoted char)
#' @return a tbl or df (depending on the input) with the interspersed headers in their own column
#' @export
#'
untangle <- function(dframe,matchstring,newCol) {
require(dplyr)
require(tidyr)
match <- enquo(match)
newCol <- quo_name(newCol)
dframe %>% mutate(!!newCol := case_when(grepl(!!matchstring,!!dframe[[1]])~!!dframe[[1]]),
removeLater = case_when(grepl(!!matchstring,!!dframe[[1]])~"yes")) %>%
fill(newCol) %>%
filter(is.na(removeLater)) %>% select(-removeLater)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment