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])) | |
} |
The only downside to that approach is the columns you might actually want to remain factors would silently be converted to characters. I usually add options(stringsAsFactors = FALSE)
to the top of my script to prevent this.
Actually, better idea: I just forced col
to be a character vector before splitting. Does that help?
It does help, and the function is great.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
stringsAsFactors bites. Recommend adding:
structure(data.frame(unlist(pieces),
data[rep(seq_along(ns), ns), -col_i], stringsAsFactors = FALSE),
names = c(col, names(data)[-col_i]))