Created
December 15, 2022 16:29
-
-
Save MayaGans/11afe34e1f0ffc321d619514d1d065a7 to your computer and use it in GitHub Desktop.
split tables with fixed columns
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
split_tables <- function(data, cols_to_freeze, max_col = 7) { | |
stopifnot( | |
"columns to fix do not exist in data" = | |
all(cols_to_freeze %in% names(data)) | |
) | |
# we don't need to table wrap if the data is less than max_col | |
if (ncol(data) <= max_col) { | |
return(data) | |
} | |
# get the columns we'll append to each data.frame | |
# needs to be a data.frame, even when only one column specified! | |
if (length(cols_to_freeze) == 1) { | |
cols_in_all <- data.frame(cols_to_freeze = data[,cols_to_keep]) | |
} else { | |
cols_in_all <- data[,cols_to_freeze] | |
} | |
# this is going to be split based on the max_col | |
other_cols <- data[ ,!(colnames(data) %in% cols_to_freeze)] | |
# number of subtable columns allowed | |
subtable_column_n <- max_col - ncol(cols_in_all) | |
# use this to find the number of tables we'll need | |
n_tables <- ceiling(ncol(other_cols)/subtable_column_n) | |
# loop over the tables and iterate | |
# what happens when this isnt a nice even number.... | |
all_tables <- list() | |
col_diff <- max_col - length(cols_to_freeze) | |
for (i in 1:n_tables) { | |
# when i is the last table we need to only fill to max columns | |
if (i == n_tables) { | |
all_tables[[i]] <- cbind( | |
cols_in_all, | |
other_cols[(col_diff*(i-1)+1):length(other_cols)] | |
) | |
# otherwise iterate to the next table i | |
} else { | |
all_tables[[i]] <- cbind( | |
cols_in_all, | |
other_cols[col_diff*(i-1)+1:col_diff*i] | |
) | |
} | |
} | |
return(all_tables) | |
} | |
# theres only 11 columns in mtcars so the total is bigger | |
# return a DF. great. | |
split_tables(mtcars, c("mpg", "vs"), 12) | |
split_tables(mtcars, c("mpg", "vs"), 5) | |
split_tables(mtcars, c("mpg", "vs"), 7) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment