英文:
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 colDef
s:
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
)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论