我想使用 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)