Skip to content

Instantly share code, notes, and snippets.

@bjulius
Created April 10, 2025 13:57
Show Gist options
  • Save bjulius/6460802f1cb49e6e46479f3823ec5130 to your computer and use it in GitHub Desktop.
Save bjulius/6460802f1cb49e6e46479f3823ec5130 to your computer and use it in GitHub Desktop.
Default Definitions for R Anaconda Code
## 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