R语言 引用格式化表的列号而不是变量名

vmpqdwk3  于 2023-09-27  发布在  其他
关注(0)|答案(2)|浏览(114)

我有一个数据框,里面是一列年度数字。为了提高效率,不必每年都更改数字,我正试图减少每年必须编辑的内容。
示例 Dataframe :

bach_STEM_wide <- data.frame(
  Name = c("Technology", "Science", "Engineering"),
  "Pct. Diff. from 2013 to 2023" = c(-5.2, 7.3, -1.8),
  "Pct. Diff. from 2022 to 2023" = c(2.1, -3.5, 1.2))

我想将这些格式规则应用于表格,但我想引用**“Pct.从2013年到2023年的差异”按其列号**而不是“Pct. 2013年至2023年的差异”
我试过:

column_number <- 2

# Refer to the column by its column number
column_data <- bach_STEM_wide[[column_number]]

formattable(bach_STEM_wide, align = "l", list(
  Name=formatter(
    "span",
    style = x ~ ifelse(x == "Technology", 
                       style(font.weight = "bold"), NA)),
  column_data  = formatter(
    "span",
    style = x ~ style(color = ifelse(x < 0 , "orange", "blue")),
    x ~ icontext(ifelse(x < 0, "arrow-down", "arrow-up"), x)), 
  one_year_pct_diff_header = formatter(
    "span",
    style = x ~ style(color = ifelse(x < 0 , "orange", "blue")),
    x ~ icontext(ifelse(x < 0, "arrow-down", "arrow-up"), x)))
)

但没成功

h7wcgrx3

h7wcgrx31#

formattable::area()可用于按索引定位小区。

library(formattable)

column_number <- 2

formattable(bach_STEM_wide, align = "l", list(
  Name=formatter(
    "span",
    style = x ~ ifelse(x == "Technology", 
                       style(font.weight = "bold"), NA)),
  area(TRUE, column_number) ~ formatter(
    "span",
    style = x ~ style(color = ifelse(x < 0 , "orange", "blue")),
    x ~ icontext(ifelse(x < 0, "arrow-down", "arrow-up"), x)), 
  one_year_pct_diff_header = formatter(
    "span",
    style = x ~ style(color = ifelse(x < 0 , "orange", "blue")),
    x ~ icontext(ifelse(x < 0, "arrow-down", "arrow-up"), x)))
)

e4yzc0pl

e4yzc0pl2#

使用setNames设置列表的名称。

formattable(
  bach_STEM_wide, align = "l", setNames(
    list(
      formatter(
        "span",
        style = x ~ ifelse(x == "Technology", style(font.weight = "bold"), NA)
      ),
      formatter(
        "span",
        style = x ~ style(color = ifelse(x < 0 , "orange", "blue")),
        x ~ icontext(ifelse(x < 0, "arrow-down", "arrow-up"), x)
      ),
      formatter(
        "span",
        style = x ~ style(color = ifelse(x < 0 , "orange", "blue")),
        x ~ icontext(ifelse(x < 0, "arrow-down", "arrow-up"), x)
      )
    ), # End of the list
    c(
      colnames(bach_STEM_wide)[1],
      colnames(bach_STEM_wide)[2],
      colnames(bach_STEM_wide)[3]
    ) # End of the name
  ) # End of setNames function
) # End of formattable

相关问题