Created
April 10, 2025 13:57
-
-
Save bjulius/6460802f1cb49e6e46479f3823ec5130 to your computer and use it in GitHub Desktop.
Default Definitions for R Anaconda Code
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
## Add imports | |
library(tidyverse) | |
## Configuration | |
options(warnPartialMatchDollar = TRUE) | |
## Define functions | |
## Pre-built utility functions | |
# Convert to tibble or data.frame | |
to_dataframe <- function(x, as_tibble=TRUE) { | |
if (inherits(x, "data.frame")) { | |
return(x) | |
} | |
if (!is_list_of_lists(x)) { | |
stop("Expected list of lists") | |
} | |
# Get column names from first row if available | |
if (length(x) > 1) { | |
col_names <- x[[1]] | |
data_rows <- x[-1] | |
} else { | |
data_rows <- x | |
col_names <- paste0("V", seq_len(length(x[[1]]))) | |
} | |
# Convert to column-wise list preserving data types | |
cols <- to_colwise_list(data_rows) | |
names(cols) <- col_names | |
# Create data frame preserving column types | |
df <- as.data.frame(cols, stringsAsFactors = FALSE) | |
if (as_tibble) { | |
if (!requireNamespace("dplyr", quietly = TRUE)) { | |
warning("Package 'dplyr' needed for tibble conversion") | |
} else { | |
return(dplyr::as_tibble(df)) | |
} | |
} | |
return(df) | |
} | |
# Convert to matrix | |
to_matrix <- function(x) { | |
if (is.matrix(x)) { | |
return(x) | |
} | |
if (!is_list_of_lists(x)) { | |
stop("Expected list of lists") | |
} | |
return(do.call(rbind, lapply(x, unlist))) | |
} | |
# Convert to colwise list of vectors | |
to_colwise_list <- function(x) { | |
if (!is_list_of_lists(x)) { | |
stop("Expected list of lists") | |
} | |
ncols <- length(x[[1]]) | |
lapply(seq_len(ncols), function(j) { | |
do.call(c, lapply(seq_along(x), function(i) x[[i]][[j]])) | |
}) | |
} | |
is_list_of_lists <- function(x) { | |
is.list(x) && length(x) > 0 && is.list(x[[1]]) | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment