R Shiny renderDataTable问题

时间:2018-02-19 23:56:07

标签: r shiny data.table

当我在R中尝试以下代码时,数据表与Button列中的不同数量的“x”按钮完美呈现。

data <- iris[1:20,1:2]
data$Button <- lapply(paste0("x",1:20),function(x) paste(rep(as.character(actionButton(x,label="x")),sample(1:3,1)),collapse="  ",sep="  "))
datatable(data)

但是当我尝试将数据框包装在闪亮的应用程序中时,一页上的每一行中始终存在相同数量的“x”按钮。可重复代码:

library(shiny)
library(DT)
server <- function(input, output) {
output$mytab <- renderDataTable({
data <- iris[1:20,1:2]
data$Button <- lapply(paste0("x",1:20),function(x) paste(rep(as.character(actionButton(x,label="x")),sample(1:3,1)),collapse="  ",sep="  "))
datatable(data)
})
}
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
),
mainPanel(dataTableOutput("mytab"))
)
)
shinyApp(ui = ui, server = server)

弹出以下错误。

Warning in `[<-.data.frame`(`*tmp*`, , j, value = list("<button id=\"x1\" type=\"button\" class=\"btn btn-default action-button\">x</button>",  :
provided 10 variables to replace 1 variables

关于如何解决这个问题的任何建议?

System Information
R version 3.4.3 (2017-11-30)
Platform: x86_64-apple-darwin15.6.0 (64-bit)
Running under: macOS High Sierra 10.13.3
[1] DT_0.2.12   shiny_1.0.5

2 个答案:

答案 0 :(得分:2)

主要问题是你的按钮ID:

library("shiny")
library("DT")
set.seed(1)

data <- iris[1:20, 1:2]
data$Button <- sapply(paste0("x", 1:20), function(x) {
  n_seq <- seq(sample(1:3, 1L))
  btns  <- sapply(n_seq, function(n) {
    id <- sprintf("%s_%s", x, n)
    as.character(actionButton(id, label = "x"))
  })
  return(paste0(btns, collapse = "  "))
})

server <- function(input, output) {
  output$mytab <- renderDataTable({
    datatable(data, escape = FALSE)
  })
}
ui <- fluidPage(
  sidebarLayout(
    sidebarPanel(
    ),
    mainPanel(dataTableOutput("mytab"))
  )
)
shinyApp(ui = ui, server = server)

enter image description here

答案 1 :(得分:0)

在从@mlegge的回答

中获取建议后,将固定代码转换为原始代码格式

1)用line6中的sapply调用替换了lapply调用

2)在第7行的数据表调用中添加了escape = FALSE参数

library(shiny)
library(DT)
server <- function(input, output) {
output$mytab <- renderDataTable({
data <- iris[1:20,1:2]
data$Button <- sapply(paste0("x",1:20),function(x) paste(rep(as.character(actionButton(x,label="x")),sample(1:3,1)),collapse="  ",sep="  "))
datatable(data,escape=FALSE)
})
}
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
),
mainPanel(dataTableOutput("mytab"))
)
)
shinyApp(ui = ui, server = server)