这是一种方法:
library(shiny)
library(DT)
ui <- fluidPage(
DTOutput("dt_table")
)
render <- c(
"function(data, type, row, meta){",
" if(type === 'display'){",
" return data + ' meters';",
" }else{",
" return data;",
" }",
"}"
)
server <- function(input, output) {
output$dt_table <- renderDT({
datatable(
iris,
options = list(
dom = 'lBfrtip',
buttons = list(
list(
extend = "copy",
exportOptions = list(orthogonal = "export")
),
list(
extend = "excel",
exportOptions = list(orthogonal = "export")
),
list(
extend = "pdf",
exportOptions = list(orthogonal = "export")
)
),
columnDefs = list(
list(targets = 2, render = JS(render))
)
),
extensions = 'Buttons'
)
})
}
shinyApp(ui = ui, server = server)
编辑
另一种方式:
tplString2 <- function(prefix, suffix, ...) {
sprintf(
"type === 'display' ? DTWidget.formatString(data, %s, %s) : data;",
DT:::jsValues(prefix), DT:::jsValues(suffix)
)
}
formatString2 <- function(table, columns, prefix = '', suffix = '') {
DT:::formatColumns(table, columns, tplString2, prefix, suffix)
}
tplDate2 <- function(method, params, ...) {
params = if (length(params) > 0) paste(',', jsonlite::toJSON(params)) else ''
sprintf(
"type === 'display' ? DTWidget.formatDate(data, %s%s) : data;",
DT:::jsValues(method), params
)
}
formatDate2 <- function(table, columns, method = 'toDateString', params = NULL) {
if (!inherits(table, 'datatables'))
stop("Invalid table argument; a table object created from datatable() was expected")
x = table$x
if (x$filter != 'none') {
if (inherits(columns, 'formula')) columns = all.vars(columns)
colnames = base::attr(x, 'colnames', exact = TRUE)
rownames = base::attr(x, 'rownames', exact = TRUE)
if (is.null(params)) params = list()
cols = sprintf("%d", DT:::name2int(columns, colnames, rownames))
x$filterDateFmt = as.list(x$filterDateFmt)
for (col in cols) x$filterDateFmt[[col]] = list(
method = method, params = jsonlite::toJSON(params)
)
table$x = x
}
DT:::formatColumns(table, columns, tplDate2, method, params)
}
library(shiny)
library(DT)
server <- function(input, output) {
output$dt_table <- renderDT({
datatable(
iris,
options = list(
dom = 'lBfrtip',
buttons = list(
list(
extend = "copy",
exportOptions = list(orthogonal = "export")
),
list(
extend = "excel",
exportOptions = list(orthogonal = "export")
),
list(
extend = "pdf",
exportOptions = list(orthogonal = "export")
)
)
),
extensions = 'Buttons'
) %>%
formatString2(columns = 1, suffix = " meters")
})
}