簡體   English   中英

在 formattable (R) 中使用逗號函數

[英]Use comma function in formattable (R)

我正在嘗試在閃亮的表輸出中使用千位分隔符。 以下是我的代碼:

UI <- dashboardPage(     
  dashboardBody(        
    fluidPage(          
      selectInput(inputId = "TableName",
                  label = "Select Data of Interest",
                  choices = list.files(path = "CSVData", pattern = "AMD_")),          
      uiOutput("Channel"),    
      formattableOutput("ResultTable")         
    )
  )
)

Server <- function(input, output){      
  output$Channel <- renderUI({        
    df <- read.csv(paste("Pathname/",input$TableName, sep = ""))        
    selectInput(inputId = "ChannelSelect",
                label = "Select Channel:",
                choices = unique(df) %>% select(Channel))),
                selected = NULL, multiple = FALSE)        
  })

  output$ResultTable <- renderFormattable({

    df <- read.csv(paste("CSVData/",input$TableName, sep = ""))
    ChanSelect <- input$ChannelSelect    
    A1 <- df %>% filter(if(ChanSelect != "All") (Channel == ChanSelect) else TRUE) %>%
      select(Channel, Amount)        
    formattable(A1, list(
      `Amount` = comma(`Amount`, digits = 0, format = "f", big.mark = ","
    ))        
  })      
}    

我的 df 是多種多樣的,但它們都采用以下格式:

data.frame("Channel" = c("A", "B", "C", "D"),
           "Amount" = c(1000000, 2000000, 3000000, 4000000 ))

問題在於它不起作用的可格式化部分。 我不知道如何使用formattable正確輸入函數comma()

有兩種方法可以做到這一點:

1. 創建自定義函數

mycomma <- function(digits = 0) {
      formatter("span", x ~ comma(x, digits = digits)
      )
    }

用於單個命名列:

formattable(df, list(`Account` = mycomma(digits=0))
  )

用於多列:

formattable(df, 
            list(area(col = c(3:6)) ~ mycomma(digits=0))
  )

2.每次都傳遞formattable函數

formattable(df, list(`Account` = formatter("span", x ~ comma(x, digits = 0))
      )

注意:您可以輕松創建自定義函數,該函數可以傳遞不同的函數,例如百分比或會計。 青年會

mysimpleformat <- function(fun = "comma", digits = 0) {
  fun <- match.fun(fun)
  formatter("span", x ~ fun(x, digits = digits)
  )
}

如果您只是想將千位標記添加到您的Amount列,您可以按如下方式進行:

df <- data.frame("Channel" = c("A", "B", "C", "D"),
                 "Amount" = c(1000000, 2000000, 3000000, 4000000 ))
df$Amount <- format(as.integer(df$Amount), big.mark=",")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM