Adding utils functions
This commit is contained in:
parent
a6298fadcd
commit
aa97a8f486
1 changed files with 66 additions and 0 deletions
66
utils.R
Normal file
66
utils.R
Normal file
|
|
@ -0,0 +1,66 @@
|
||||||
|
library(knitr)
|
||||||
|
library(kableExtra)
|
||||||
|
|
||||||
|
ellipse_table <- function(df, nr = 5, nc = 5, format = "latex") {
|
||||||
|
nrows <- nrow(df)
|
||||||
|
ncols <- ncol(df)
|
||||||
|
|
||||||
|
# Ellipsis symbols depending on format
|
||||||
|
if (format == "latex") {
|
||||||
|
h_ellipsis <- "$\\dots$" # horizontal (for columns)
|
||||||
|
v_ellipsis <- "$\\vdots$" # vertical (for rows)
|
||||||
|
both_ellipsis <- "$\\ddots$" # for center cell (optional)
|
||||||
|
} else {
|
||||||
|
h_ellipsis <- "..."
|
||||||
|
v_ellipsis <- "..."
|
||||||
|
both_ellipsis <- "..."
|
||||||
|
}
|
||||||
|
|
||||||
|
# Select top/bottom rows
|
||||||
|
row_idx <- c(
|
||||||
|
seq_len(ceiling(nr / 2)),
|
||||||
|
nrows - floor(nr / 2) + 1:nr - nr
|
||||||
|
)
|
||||||
|
row_idx <- unique(pmax(pmin(row_idx, nrows), 1)) # clamp
|
||||||
|
|
||||||
|
# Select left/right cols
|
||||||
|
col_idx <- c(
|
||||||
|
seq_len(ceiling(nc / 2)),
|
||||||
|
ncols - floor(nc / 2) + 1:nc - nc
|
||||||
|
)
|
||||||
|
col_idx <- unique(pmax(pmin(col_idx, ncols), 1))
|
||||||
|
|
||||||
|
# Subset
|
||||||
|
sub_df <- df[row_idx, col_idx, drop = FALSE]
|
||||||
|
|
||||||
|
# Insert ellipsis row if needed
|
||||||
|
if (nrows > nr) {
|
||||||
|
ellipsis_row <- as.list(rep(h_ellipsis, length(col_idx)))
|
||||||
|
sub_df <- rbind(
|
||||||
|
sub_df[1:ceiling(nr / 2), , drop = FALSE],
|
||||||
|
ellipsis_row,
|
||||||
|
sub_df[(ceiling(nr / 2) + 1):nrow(sub_df), , drop = FALSE]
|
||||||
|
)
|
||||||
|
rownames(sub_df)[ceiling(nr / 2) + 1] <- v_ellipsis
|
||||||
|
}
|
||||||
|
|
||||||
|
# Insert ellipsis col if needed
|
||||||
|
if (ncols > nc) {
|
||||||
|
ellipsis_col <- rep(v_ellipsis, nrow(sub_df))
|
||||||
|
sub_df <- cbind(
|
||||||
|
sub_df[, 1:ceiling(nc / 2), drop = FALSE],
|
||||||
|
"..." = ellipsis_col,
|
||||||
|
sub_df[, (ceiling(nc / 2) + 1):ncol(sub_df), drop = FALSE]
|
||||||
|
)
|
||||||
|
names(sub_df)[ceiling(nc / 2) + 1] <- h_ellipsis
|
||||||
|
}
|
||||||
|
|
||||||
|
# # Optionally replace center cell with diagonal dots (nice touch in latex)
|
||||||
|
# if (format == "latex" && nrows > nr && ncols > nc) {
|
||||||
|
# mid_r <- ceiling(nrow(sub_df) / 2)
|
||||||
|
# mid_c <- ceiling(ncol(sub_df) / 2)
|
||||||
|
# sub_df[mid_r, mid_c] <- both_ellipsis
|
||||||
|
# }
|
||||||
|
# Print with kable
|
||||||
|
return(sub_df)
|
||||||
|
}
|
||||||
Loading…
Add table
Reference in a new issue