Skip to content

Instantly share code, notes, and snippets.

@njtierney
Forked from aammd/matrix_to_data.frame.R
Created January 4, 2017 01:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save njtierney/80b5c485d797617d5ae01332a2714a57 to your computer and use it in GitHub Desktop.
Save njtierney/80b5c485d797617d5ae01332a2714a57 to your computer and use it in GitHub Desktop.
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