我有一个 Shiny 的 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))
})
这适用于指定的所有格式选项,但 justify 除外。所有数字列在输出中左对齐。
任何人都可以解释为什么?
最佳答案
你可以包装你的 tableOutput
与 uiOutput
(又名 htmlOutput
)以更改 align
数据变化时的参数。这是一个例子。
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))
关于r - Shiny 的 R renderTable 右对齐,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23613803/