将多列格式化为百分比。

huangapple go评论68阅读模式
英文:

R reactable format multiple columns as percentage

问题

我想用reactable包将我的数据框中的几列格式化为百分比。我知道如果逐行指定所有列,可以如何做到这一点,但我希望只需指定起始列号即可实现相同的输出,例如从第二列开始。

reactable(
  data.frame(
    id = seq(1, 10, 1),
    sh = seq(.1, 1, .1),
    ar = seq(.1, 1, .1),
    br = seq(.1, 1, .1)
  ), 
  columns = list(
    sh = colDef(format = colFormat(percent = TRUE, digits = 1)),
    ar = colDef(format = colFormat(percent = TRUE, digits = 1)),
    br = colDef(format = colFormat(percent = TRUE, digits = 1))
    )
  )
英文:

I'd like format several columns in my dataframe as percentage with reactable package. I know how can I do it if I specify all of them row by row, but I'd like to achieve same output only if I specify starting column number, in this case from 2nd column.

reactable(
  data.frame(
    id = seq(1, 10, 1),
    sh = seq(.1, 1, .1),
    ar = seq(.1, 1, .1),
    br = seq(.1, 1, .1)
  ), 
  columns = list(
    sh = colDef(format = colFormat(percent = TRUE, digits = 1)),
    ar = colDef(format = colFormat(percent = TRUE, digits = 1)),
    br = colDef(format = colFormat(percent = TRUE, digits = 1))
    )
  )

答案1

得分: 0

一个选项是使用例如 lapply 来创建一个命名的 colDef 列表:

library(reactable)

dat <- data.frame(
  id = seq(1, 10, 1),
  sh = seq(.1, 1, .1),
  ar = seq(.1, 1, .1),
  br = seq(.1, 1, .1)
)

cols <- names(dat)[-1]
col_defs <- lapply(
  cols,
  \(x) colDef(format = colFormat(percent = TRUE, digits = 1))
)
names(col_defs) <- cols

reactable(
  dat,
  columns = col_defs
)

将多列格式化为百分比。

英文:

One option would be to use e.g. lapply to create a named list of colDefs:

library(reactable)

dat &lt;- data.frame(
  id = seq(1, 10, 1),
  sh = seq(.1, 1, .1),
  ar = seq(.1, 1, .1),
  br = seq(.1, 1, .1)
)

cols &lt;- names(dat)[-1]
col_defs &lt;- lapply(
  cols,
  \(x) colDef(format = colFormat(percent = TRUE, digits = 1))
)
names(col_defs) &lt;- cols

reactable(
  dat,
  columns = col_defs
)

将多列格式化为百分比。

huangapple
  • 本文由 发表于 2023年7月27日 23:03:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/76781066.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定