我正在寻找一种方法将按钮添加到 r Shiny 中的数据表:
每次单击时向数据表添加一个空列(以及首先创建表的数据框
哪个用户可以自己填写
带有数字或文本值
并设置自己的列名来描述条目值的类型。
例如,将实验室笔记记录手动添加到 Shiny 的应用程序中已经存在的仪器数据中
我在问,如果一个比我有更好线索的更熟练的人知道如何做到这一点。
我已经阅读了一堆页面,但我发现的示例充其量提供了 1 个具有固定名称的固定空列
包中的虚拟表:
图书馆(DT)
ui <- basicPage(
h2("The mtcars data"),
DT::dataTableOutput("mytable")
)
server <- function(input, output) {
output$mytable = DT::renderDataTable({
mtcars
})
}
shinyApp(ui, server)
最佳答案
您可以使用按钮将新列添加到 R Shiny 数据表中,如下所示:
ui <- fluidPage(
h2("The mtcars data"),
DT::dataTableOutput("mytable"),
textInput('NewCol', 'Enter new column name'),
radioButtons("type", "Column type:",
c("Integer" = "integer",
"Floating point" = "numeric",
"Text" = "character")),
actionButton("goButton", "Update Table")
)
server <- function(input, output) {
mydata <- mtcars
output$mytable = DT::renderDataTable(df())
df <- eventReactive(input$goButton, {
if(input$NewCol!="" && !is.null(input$NewCol) && input$goButton>0){
if (input$type == "integer") v1 <- integer(NROW(mydata))
if (input$type == "numeric") v1 <- numeric(NROW(mydata))
if (input$type == "character") v1 <- character(NROW(mydata))
newcol <- data.frame(v1)
names(newcol) <- input$NewCol
mydata <<- cbind(mydata, newcol)
}
mydata
}, ignoreNULL = FALSE)
}
shinyApp(ui,server)
如果您还需要交互式编辑单元格的内容,可以使用
renderRHandsontable
而不是 renderDataTable
.像这样:library(rhandsontable)
ui <- fluidPage(
h2("The mtcars data"),
rHandsontableOutput("mytable"),
textInput('NewCol', 'Enter new column name'),
radioButtons("type", "Column type:",
c("Integer" = "integer",
"Floating point" = "numeric",
"Text" = "character")),
actionButton("goButton", "Update Table")
)
server <- function(input, output) {
mydata <- mtcars[1:5,]
output$mytable = renderRHandsontable(df())
df <- eventReactive(input$goButton, {
if(input$NewCol!="" && !is.null(input$NewCol) && input$goButton>0){
if (input$type == "integer") v1 <- integer(NROW(mydata))
if (input$type == "numeric") v1 <- numeric(NROW(mydata))
if (input$type == "character") v1 <- character(NROW(mydata))
newcol <- data.frame(v1)
names(newcol) <- input$NewCol
mydata <<- cbind(mydata, newcol)
}
rhandsontable(mydata, stretchH = "all")
}, ignoreNULL = FALSE)
observe(if (!is.null(input$mytable)) mydata <<- hot_to_r(input$mytable))
}
shinyApp(ui,server)
关于r - 将条目列添加到 r Shiny 数据表的按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48471042/