R DT 数据表使用 formatRound 逐行格式化数字

问题描述 投票:0回答:1

我面临以下问题:我想在 Shiny 应用程序中使用 R 包 DT 格式化数据表。我希望第一行中的数字四舍五入为 0 位,其他行中的数字四舍五入为 2 位

data <- data.frame(c1 = c(123.456, 789.123, 456.55),
c2 = c(123.456, 789.123, 456.55))
# this does not work
datatable(data) %>% formatRound(1:2, digits=0, rows=1) %>% formatRound(1:2, digits=2, rows=1:2)
# this also does not work
datatable(data) %>% formatRound(1:2,digits=c(0,2,2))

你能帮我吗?有可能实现这一目标吗?我想也许用一些 JS 应该是可能的,但我是 js 的新手......

提前感谢您的指导

javascript r datatable dt
1个回答
0
投票

虽然对于大型数据集来说效率不高,但如果您的数据集不是很大(否则生成输出可能会很慢),您可以尝试:

library(DT)

data <- data.frame(c1 = c(123.456, 789.123, 456.55),
                   c2 = c(123.456, 789.123, 456.55))

formatRows <- function(df) {
    for (i in 1:nrow(df)) {
        if (i == 1) {
            df[i, 1:2] <- round(df[i, 1:2], 0)
        } else {
            df[i, 1:2] <- round(df[i, 1:2], 2)
        }
    }
    return(df)
}

#apply the func
formattedData <- formatRows(data)

#convert into a datatable
datatable(formattedData)

结果:

© www.soinside.com 2019 - 2024. All rights reserved.