Last active
August 29, 2015 14:07
-
-
Save aaronwolen/13eca5b969689c6a2bed to your computer and use it in GitHub Desktop.
Extract and append multiple values embedded in rows
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
# Extract and append multiple values embedded in rows | |
# | |
# data: data.frame | |
# col: column name containing embedded values | |
# sep: regular expression to split column by | |
# | |
# df <- data.frame(key = c("a", "a;b", "a;b;c"), val = 1:3) | |
# unembed(df, "key", ";") | |
unembed <- function(data, col, sep, ...) { | |
stopifnot(is.data.frame(data)) | |
col_i <- which(names(data) == col) | |
data[[col]] <- as.character(data[[col]]) | |
pieces <- strsplit(data[[col]], sep, ...) | |
ns <- vapply(pieces, length, integer(1)) | |
structure(data.frame(unlist(pieces), | |
data[rep(seq_along(ns), ns), -col_i]), | |
names = c(col, names(data)[-col_i])) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
It does help, and the function is great.