Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
cantrip to turn a matrix into a data.frame, assuming that the first row of the matrix contains a header row
matrix_to_df_firstline_header <- function(mat){
requireNamespace("purrr")
mat %>%
## cut columns into lists
apply(2, function(s) list(s)) %>%
flatten %>%
map(flatten_chr) %>%
## set names to the first element of the list
{set_names(x = map(., ~ .x[-1]),
nm = map_chr(., 1))} %>%
## create data.frames
as.data.frame(stringsAsFactors = FALSE)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment