0

我想使用 gt 创建一个通用表生成函数,该函数标记传递的数据表中的列,但我想不出一种方法来获取 gt cols_label 步骤以允许我遍历列。有小费吗?

这是我的代码:

dtExample = data.table(
  sGEOID = c("A","B","B",'C'),
  dDate = c('2020-05-15', '2020-05-16', '2020-05-17', '2020-05-15'),
  iVal = 1:4
)

lVarDesc <- list(sGEOID = "Location ID",
                 dDate = "Obs. Date",
                 iVal = "Value"
)

lcCols <- c('dDate', 'iVal')

# Version 1: dummy version that labels only one column with each available label
# works
ltResTable <- gt(data=dtExample[, ..lcCols])
for (lasVarName in lcCols) {
  ltResTable <- ltResTable %>% cols_label(iVal = lVarDesc[[eval(lasVarName)]])
}
print(ltResTable)

# Version 2: attempt to attach labels to each column
# fails
ltResTable <- gt(data=dtExample[, ..lcCols])
for (lasVarName in lcCols) {
  ltResTable <- ltResTable %>% cols_label(eval(lasVarName) = lVarDesc[[eval(lasVarName)]])
}
print(ltResTable)

# Version 3: no loop, column name in quotes
# works
ltResTable <- gt(data=dtExample[, ..lcCols])
lasVarName <- 'iVal'
ltResTable <- ltResTable %>% cols_label('iVal' = lVarDesc[[eval(lasVarName)]])
print(ltResTable)

# Version 4: no loop, but eval function
# fails
ltResTable <- gt(data=dtExample[, ..lcCols])
lasVarName <- 'iVal'
ltResTable <- ltResTable %>% cols_label(eval(lasVarName) = lVarDesc[[eval(lasVarName)]])
print(ltResTable)

# Version 5: attempt to label all columns, even absent ones
# fails
ltResTable <- gt(data=dtExample[, ..lcCols])
ltResTable <- ltResTable %>% cols_label(sGEOID = "Location ID",
                                        dDate = "Obs. Date",
                                        iVal = "Value"
)
print(ltResTable)
4

1 回答 1

0

这可能既丑陋又脆弱,但我认为它会起作用:

liNumCols <- length(lcCols)
ltResTable <- gt(data=dtExample[, ..lcCols])

for (liColNum in 1:liNumCols) {
  lasVarName <- ltResTable$`_boxhead`$var[liColNum]
  ltResTable$`_boxhead`$column_label[liColNum] <- lVarDesc[[eval(lasVarName)]]
}
print(ltResTable)
于 2020-05-22T03:27:34.333 回答