我有一个闪亮的 R 应用程序,其中使用“renderTable”函数来渲染动态创建的表。该表在一种情况下可以具有 3 个字符列和 4 个数字列,在另一种情况下可以具有 2 个字符列和 2 个数字列。ui.R 的 renderTable 代码是:
output$table1 <- renderTable({
d1<-data()
print(format(d1, big.mark=",", scientific=FALSE,justify="right", nsmall=0))
})
Run Code Online (Sandbox Code Playgroud)
这适用于除 justify 之外指定的所有格式选项。所有数字列在输出中均左对齐。
谁能解释一下为什么?
您可以用(又名)包装您的tableOutput内容,以便在数据更改时更改参数。这是一个例子。uiOutputhtmlOutputalign
library(shiny)
server <- function(input, output, session) {
output$table_wrapped = renderUI({
# this table can be reactive since it is inside a render function
reactiveTable = data.frame(
name=sapply(1:input$nrows, function(x) paste(
rep(letters[x], x),
collapse=''))
)
for( i in 1:input$ncols )
reactiveTable[letters[i]] = seq(100, 100*input$nrows, by = 100)
# calculate alignment vector (something like "lrrrrr")
align = paste(rep('l', ncol(reactiveTable)))
numeric_columns = which(as.logical(lapply(reactiveTable, is.numeric)))
align[numeric_columns] = "r"
align = paste(align, collapse ="")
# create tableoutput. Since this is inside a render Function,
# the alignment changes with the inputs
output$table <- renderTable({reactiveTable}, align = align)
# return the tableOutput
tableOutput('table')
})
}
ui <- fluidPage(
inputPanel(
sliderInput("ncols", "Number of numeric columns", 4, 10, 4),
sliderInput("nrows", "Number of rows", 4, 10, 4)
),
uiOutput('table_wrapped')
)
runApp(list(ui=ui, server=server))
Run Code Online (Sandbox Code Playgroud)
如果列数始终相同,您可以使用 的参数align,renderTable例如:
library(shiny)
server <- function(input, output, session) {
output$tab <- renderTable({
data.frame(a=seq(100, 1000, by=100), b=sapply(1:10, function(x) paste(rep(letters[x], x), collapse='')))
}, align='rrr')
}
ui <- fluidPage(
tableOutput('tab')
)
runApp(list(ui=ui, server=server))
Run Code Online (Sandbox Code Playgroud)
请注意,您还指定了行名称的对齐方式。