-
Notifications
You must be signed in to change notification settings - Fork 0
/
functions.R
72 lines (49 loc) · 1.6 KB
/
functions.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# Split a df in half, and bind them back together to make one table with
# twice the number of columns, but half the rows. Adds an extra blank
# row to the second df if needed.
split_table <- function(x) {
split1 <- x |>
head(ceiling(nrow(x) / 2))
colnames(split1) <- paste(colnames(split1), "_1", sep = "")
split2 <- x |>
tail(floor(nrow(x) / 2))
colnames(split2) <- paste(colnames(split2), "_2", sep = "")
if (nrow(split1) != nrow(split2)) {
split2 <- add_row(split2)
}
return(final <- bind_cols(split1, split2))
}
# Use with split_table(). After splitting a table in half, you can strip off
# the last two characters of the columns with the "_1" and "_2".
split_cols_label <- function(x) {
stopifnot("x should be a gt" = inherits(x, "gt_tbl"))
x |>
cols_label_with(
fn = ~ stringr::str_remove(., "_1"),
) |>
cols_label_with(
fn = ~ stringr::str_remove(., "_2")
)
}
# demo of split_table() and split_cols_label()
library(tidyverse)
library(gt)
tst <- tibble(rank = 1:19, upper = LETTERS[1:19], lower = letters[1:19])
split_tst <- split_table(tst)
gt(split_tst) |>
split_cols_label()
# Strip out specific text in displayed column labels
strip_cols_label <- function(x, string) {
stopifnot("x should be a gt" = inherits(x, "gt_tbl"))
x |>
cols_label_with(
fn = ~ stringr::str_remove(., string)
)
}
replace_cols_label <- function(x, string, replacement) {
stopifnot("x should be a gt" = inherits(x, "gt_tbl"))
x |>
cols_label_with(
fn = ~ stringr::str_replace(., string, replacement)
)
}