Hello everyone, I'm building a Shiny app to edit uploaded data and modify them by using rhandsontable package.
I'd like to allow the user to add/remove columns. Despite I could introduce the possibility to add columns with different types of classes (integer, numeric, character), I could not be able to allow the user the remove columns from the uploaded dataset. (it is possible by default to remove/add the rows).
I tried to use the command useTypes =TRUE (or useTypes == TRUE).
I built this reprex, as an example.
library(shiny)
library(rhandsontable)
library(DT)
ui <- fluidPage(
tabPanel("Databases", icon = icon("users"),
sidebarLayout(
sidebarPanel(
conditionalPanel('input.dataset === "Import Data"',
textInput('NewCol', 'Enter new column name'),
radioButtons("type", "Column type:",
c("Integer" = "integer",
"Numeric" = "numeric",
"Text" = "character")),
actionButton("goButton", "Update Table")
)),
mainPanel(
tabsetPanel(id='dataset',
tabPanel(title = "Import Data",
rHandsontableOutput('mytable')
))))))
server <- function(input, output,session) {
indat <- reactiveValues()
indat$data <- data.frame(
a = c(3.58, 3.6, 3.65, 3.72),
b = c(0.0015, 0.0065, 7e-04, 0.0012),
c = c(0.0014, 0.0058, 9e-04, 3e-04),
d = c(0.0015, 0.0061, 6e-04, 7e-04))
observe({
if(!is.null(input$mytable)){
indat$data <- hot_to_r(input$mytable)
} else {
return(NULL)}
})
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(indat$data))
if (input$type == "numeric") v1 <- numeric(NROW(indat$data))
if (input$type == "character") v1 <- character(NROW(indat$data))
newcol <- data.frame(v1)
names(newcol) <- input$NewCol
indat$data <<- cbind(newcol,indat$data)
}
rhandsontable(indat$data, useTypes = TRUE, rowHeaderWidth = 200, stretchH = "all")%>%
hot_context_menu(allowRowEdit = TRUE,
allowColEdit = TRUE,
customOpts = list(
csv = list(name = "Download to CSV",
callback = htmlwidgets::JS(
"function (key, options) {
var csv = csvString(this, sep=',', dec='.');
var link = document.createElement('a');
link.setAttribute('href', 'data:text/plain;charset=utf-8,' +
encodeURIComponent(csv));
link.setAttribute('download', 'data.csv');
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}")),
search = list(name = "Search",
callback = htmlwidgets::JS(
"function (key, options) {
var srch = prompt('Search criteria');
this.search.query(srch);
this.render();
}")))) %>%
hot_cols(columnSorting = TRUE) %>%
hot_table(highlightCol = TRUE, highlightRow = TRUE)
}, ignoreNULL = TRUE)
mydataset <- eventReactive(input$goButton, {
return(indat$data)
})
}
shinyApp(ui, server)
I'd be very grateful if anybody could attend to this matter!