I am trying to write a function that produces a table using the gt() function. My reprex succeeds in producing a simple table by transposing a data frame and creating a table from it. But when I try to convert this code into a function, in order to generalize for a variety of different data frames, I get stuck trying to blank-out the first column name and make the other column names bold. How can I refer to the columns properly in the cols_label() function in a general way? Any help much appreciated. Phil

\library(gt)
library(tidyverse)

# Create example data frame
blank <- c("colnam1","colnam2","colnam3","colnam4","colnam5")
rownam1 <- 1:5
rownam2 <- rnorm(5)
df <- data.frame(blank=blank,rownam1=rownam1,rownam2=rownam2)

# Transpose the data frame and prepare it for gt()
tbl_df <- as.data.frame(t(df))
hold <- rownames(tbl_df)
colnam <- tbl_df[1,]
colnames(tbl_df) <- colnam
tbl_df <- tbl_df[2:nrow(tbl_df),]
rownames(tbl_df) <- NULL
tbl_df <- mutate(tbl_df,blank=hold[2:length(hold)])
tbl_df <- select(tbl_df,blank,everything())

# Create the gt() table - this works
gt_tbl <- gt(data=tbl_df)
gt_tbl <- tab_options(gt_tbl,table.font.size=24,
    container.width = 900)
gt_tbl <- tab_header(gt_tbl,
    title=md(html(paste0("**","Example title","**"))))
gt_tbl <- cols_align(gt_tbl,
    align=c("left"),
    columns=vars(`blank`))
gt_tbl <- cols_label(gt_tbl,
    blank="",
    colnam1=md("**colnam1**"),
    colnam2=md("**colnam2**"),
    colnam3=md("**colnam3**"),
    colnam4=md("**colnam4**"),
    colnam5=md("**colnam5**"))
gt_tbl

# Now do the same = with a function
tblfunc <- function(df) {
  gt_tbl <- gt(data=df)
  gt_tbl <- tab_options(gt_tbl,table.font.size=24,
      container.width = 900)
  gt_tbl <- tab_header(gt_tbl,
      title=md(html(paste0("**","Example title","**"))))
  gt_tbl <- cols_align(gt_tbl,
      align=c("left"),
      columns=vars(`blank`))
  gt_tbl <- cols_label(gt_tbl,
    ????)
}

______________________________________________
R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.

Reply via email to