unable to reset the textinput and selectinput in r shiny app - r

Unable to reset the textinput and selectinput. I tried to create the action button reset. Also used observeEvent. could you please help. I want to understand why the reset with observeEvent is not working, also when I manually clear the textinput, the app gives error. Any reason
libraries:
library(shiny)
library(shinyjs)
library(magrittr)
library(tidyverse)
UI part
# Define UI for application that draws a histogram
ui <- fluidPage(
# Application title
titlePanel("Package with datasets and functions"),
div(id='form',
# Sidebar with a slider input for number of bins
sidebarLayout(
sidebarPanel(
textInput('pkg','Package Name', value = NULL),
actionButton("update", "Update View"),
actionButton("reset", "Reset inputs"),
helpText('Please enter the package name for which you want to see the list of datasets and functions (with parameters)'),
br(),
# br(),
selectInput('dat','Datasets', choices = NULL, selected = NULL)
),
# Show a plot of the generated distribution
mainPanel(
tabsetPanel(
id = 'dataset',
tabPanel("List of Datasets in the Package", DTOutput("dataset1")),
tabPanel("Datasets View", DTOutput("dataset2")),
tabPanel("List of Functions with Parameters in the Package", verbatimTextOutput('func'))
)
)
)
)
)
server part
# Define server logic required to draw a histogram
server <- function(input, output, session) {
pkgs <- reactive({input$pkg})
observeEvent(input$reset, {
#pkgs() <- NULL
updateSelectInput(session, 'dat','Datasets', choices = NULL, selected = NULL)
updateTextInput('pkg','Package Name', value = NULL)
})
#
# if (!is.null(pkgs())){
df <- reactive({
# pksis <- require(input$pkg)
# cat(pksis)
# if (input$pkg %in% rownames(installed.packages()) == TRUE) {
data_name1 <- data(package=input$pkg)
data_name2 <- as_tibble(data_name1$results) %>% rename(name=Item, label=Title) %>% select(-LibPath, -Package)
data_name2
# } else {
# install.packages(input$pkg)
# library(input$pkg)
# data_name1 <- data(package=input$pkg)
# data_name2 <- as_tibble(data_name1$results) %>% rename(name=Item, label=Title) %>% select(-LibPath, -Package)
# data_name2
# }
})
# }
obse <- eventReactive(input$update, { df() })
funct <- eventReactive(input$update, { paste0('package:',input$pkg) })
# if (!is.null(pkg1())){
observe({
req(obse())
updateSelectInput(session, inputId = "dat", label = "Datasets", choices = c(df()$name), selected = df()$name[1])
})
# }
df2 <- reactive({
req(obse())
e <- new.env()
library(package = input$pkg, character.only = TRUE)
out <- data(list=input$dat, package = input$pkg, envir = e)
e[[out]]
# new <- input$dat
# data(new, package = input$pkg)
# cat(new)
})
output$dataset1 <- renderDataTable({
DT::datatable(obse())
})
output$dataset2 <- renderDataTable({
df2()
})
output$func <- renderPrint({
lsf.str(funct())
})
observeEvent(input$reset,{
output$dataset1 <- renderDataTable({
})
output$dataset2 <- renderDataTable({
})
output$func <- renderPrint({
})
})
}
# Run the application
# undebug(shinyApp)
shinyApp(ui = ui, server = server)

The following code makes the order of update and reset clearer in the server part.
library(shiny)
library(shinyjs)
library(magrittr)
library(tidyverse)
require(DT)
ui <- fluidPage(
# Application title
titlePanel("Package with datasets and functions"),
div(id='form',
# Sidebar with a slider input for number of bins
sidebarLayout(
sidebarPanel(
textInput('pkg','Package Name', value = NULL),
actionButton("update", "Update View"),
actionButton("reset", "Reset inputs"),
helpText('Please enter the package name for which you want to see the list of datasets and functions (with parameters)'),
br(),
# br(),
selectInput('dat','Datasets', choices = NULL, selected = NULL)
),
# Show a plot of the generated distribution
mainPanel(
tabsetPanel(
id = 'dataset',
tabPanel("List of Datasets in the Package", DTOutput("dataset1")),
tabPanel("Datasets View", DTOutput("dataset2")),
tabPanel("List of Functions with Parameters in the Package", verbatimTextOutput('func'))
)
)
)
)
)
server <- function(input, output, session) {
pkgs <- reactive({
req(input$pkg)
})
##### update
observeEvent(input$update, {
updateTextInput(inputId = 'pkg', value = pkgs())
# check if this_package is installed
if(system.file(package = pkgs()) == ""){
updateSelectInput(session, 'dat', choices = NULL , selected = NULL)
}
else{
# data sets in the package
data_pkg <- data(package = pkgs())
# names of data sets in the package
data_names <- data_pkg$results[, "Item"]
updateSelectInput(session, 'dat', choices = data_names, selected = data_names[1])
### dataset1 - data names
output$dataset1 <- renderDataTable({
DT::datatable(data.frame(data_names))
})
### dataset3 - function list
funs <- paste0('package:', pkgs())
output$func <- renderPrint({
lsf.str(funs)
})
}
})
### dataset2 - selected dataset
data_name <- reactive({
req(input$dat)
})
output$dataset2 <- renderDataTable({
e <- new.env()
library(package = pkgs(), character.only = TRUE)
out <- data(list=data_name(), package = pkgs(), envir = e)
d2 <- e[[out]]
# some datasets are 3-d, e.g., "ozone" in package "plyr"
if(length(dim(d2)) == 3){
d2 <- d2[, , 1]
}
DT::datatable(d2)
})
##### reset
observeEvent(input$reset, {
updateTextInput(inputId = 'pkg',value = NULL)
updateSelectInput(session, 'dat', choices = NULL , selected = NULL)
output$dataset1 <- renderDataTable({
DT::datatable(data.frame("No package selected" = NULL))
})
})
}
# Run the application
shinyApp(ui = ui, server = server)

Related

Filtering data according to column name and respective column's values in shiny

I am new in shiny, and maybe it can be easy but I could not make it, so I want to select column name firstly and in second box, it show unique values for selected column, and when choosing any values data table and plot appearing, plot will based on filtered part, thats why it is not hard but my main difficulties to extract interactive filter for data and and in default version, it should be whole data. I share what I have dont it is not working and not correct (this code is without data, I can not share data), I corrected some codes, now I can filter according to one value, but I want to see whole data in default version.
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
pickerInput("eda_col", "Select variable",
choices = c("col 1", "col 2", "col 3", "col 4"), selected = character(0)),
uiOutput("varselect"),
# selectInput("xSelector", label = "Select x axis", choices = xAxischoices),
# selectInput("ySelector", label = "Select the y axis", choices = yAxischoices),
# selectInput("cyLSelector", label = "Select a cylinder", choices = cylinderChoices),
actionButton("RefreshPlot", label = "Refresh")
),
mainPanel(
dataTableOutput("datatable1")
)
)
)
server <- function(input, output) {
output$varselect <- renderUI({
vars <- d[[as.name(input$eda_col)]]
checkboxGroupInput("level_choice", "Select factors to include", unique(vars))
})
# vars_r <- reactive({
# input$vars
# })
#
#
# res_mod <- callModule(
# module = selectizeGroupServer,
# id = "my-filters",
# data = d,
# vars = vars_r
# )
#
# output$table <- DT::renderDataTable({
# req(res_mod())
# res_mod()
# })
filteredData <- reactive({
filteredData <- d %>% filter((!! rlang:: sym(input$eda_col)) == input$level_choice)
return(filteredData)
})
output$datatable1 <- renderDataTable({
datatable(filteredData())
})
}
shinyApp(ui, server)
Please present a full MRE in the future. I have presented your requirements using available dataset gapminder. If this is not your expectation, please update your question using mtcars or gapminder data. Try this
library(gapminder)
choices <- names(gapminder)[1:2]
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
pickerInput("eda_col", "Select variable",
choices = choices, selected = character(0)),
uiOutput("varselect"),
# selectInput("xSelector", label = "Select x axis", choices = xAxischoices),
# selectInput("ySelector", label = "Select the y axis", choices = yAxischoices),
# selectInput("cyLSelector", label = "Select a cylinder", choices = cylinderChoices),
actionButton("RefreshPlot", label = "Refresh")
),
mainPanel(
dataTableOutput("datatable1")
)
)
)
server <- function(input, output) {
output$varselect <- renderUI({
if (is.null(input$eda_col)) vars <- names(gapminder)[1] ## define your default variable selection
else vars <- gapminder[[as.name(input$eda_col)]]
checkboxGroupInput("level_choice", "Select factors to include", unique(vars))
})
# vars_r <- reactive({
# input$vars
# })
#
#
# res_mod <- callModule(
# module = selectizeGroupServer,
# id = "my-filters",
# data = d,
# vars = vars_r
# )
#
# output$table <- DT::renderDataTable({
# req(res_mod())
# res_mod()
# })
filteredData <- reactive({
filteredData <- gapminder %>% filter((!! rlang:: sym(input$eda_col)) %in% input$level_choice)
return(filteredData)
})
output$datatable1 <- renderDataTable({
datatable(filteredData())
})
}
shinyApp(ui, server)

How to save and load state with insertUI modules?

I'm trying to save and load state of a shiny app using bookmarks. However, it doesn't work and I wonder whether it is because of inserting dynamic UI. If there are other ways to save and load dynamically rendered ui and resulting output, that would be great too. I don't know where to start and this is as far as I could come.
Simple example
library(shiny)
ui <- function(request){fluidPage(
actionButton("add", "Add UI"),
bookmarkButton()
)}
# Server logic
server <- function(input, output, session) {
observeEvent(input$add, {
insertUI(
selector = "#add",
where = "afterEnd",
ui = textInput(paste0("txt", input$add),
"Insert some text")
)
})
}
# Complete app with UI and server components
shinyApp(ui, server, enableBookmarking = "server")
Complex example
library(shiny)
one_plotUI <- function(id) {
ns <- NS(id)
plotOutput(ns("plot"))
}
one_plot <- function(id, x, y, type, breaks, break_counts) {
moduleServer(
id,
function(input, output, session) {
output$plot <- renderPlot({
if (type == "scatter") {
plot(x, y)
} else {
if (breaks == "custom") {
breaks <- break_counts
}
hist(x, breaks = breaks)
}
})
}
)
}
ui <- fluidPage(
sidebarPanel(
bookmarkButton(),
selectInput("plotType", "Plot Type",
c(Scatter = "scatter", Histogram = "hist")
),
# Only show this panel if the plot type is a histogram
conditionalPanel(
condition = "input.plotType == 'hist'",
selectInput(
"breaks", "Breaks",
c("Sturges", "Scott", "Freedman-Diaconis", "[Custom]" = "custom")
),
# Only show this panel if Custom is selected
conditionalPanel(
condition = "input.breaks == 'custom'",
sliderInput("breakCount", "Break Count", min = 1, max = 50, value = 10)
)
),
actionButton("make_plot", "Insert new plot")
),
mainPanel(
div(id = "add_here")
)
)
server <- function(input, output) {
x <- rnorm(100)
y <- rnorm(100)
counter_plots <- 1
observeEvent(input$make_plot, {
current_id <- paste0("plot_", counter_plots)
# call the logic for one plot
one_plot(id = current_id,
x = x,
y = y,
type = input$plotType,
breaks = input$breaks,
break_counts = input$breakCount)
# show the plot
insertUI(selector = "#add_here",
ui = one_plotUI(current_id))
# update the counter
counter_plots <<- counter_plots + 1
})
}
shinyApp(ui, server, enableBookmarking = "server")
edit: Found another solution emulating what insertUI does but with renderUI:
library(shiny)
library(purrr)
ui <- function(request){fluidPage(
actionButton("add", "Add UI"),
uiOutput('dynamic_ui'),
bookmarkButton()
)}
# Server logic
server <- function(input, output, session) {
input_contents <- reactive({reactiveValuesToList(input)})
observeEvent(input$add, {
# a new ui will be rendered with one extra input each time add button is pressed
output$dynamic_ui <- renderUI({
map(1:input$add, ~textInput(inputId = paste0("txt", .x), label = paste0("txt", .x) ))
})
#add the old values, otherwise all the inputs will be empty agin.
input_contents() %>%
names() %>%
map(~ updateTextInput(session = session, inputId = .x, label = .x, value = input_contents()[[.x]]))
})
}
# Complete app with UI and server components
shinyApp(ui, server, enableBookmarking = "server")
insertUI might be broken. The only way i could "fix" it was to drop function(request) of the ui, that caused that all the values in the inputs have to be saved between stances (in state$values$input_restore). Also a warning is showed in the console, but it doesn't affect the functionality.
library(shiny)
library(tidyverse)
library(stringr)
ui <- fluidPage(
actionButton("add", "Add UI"),
uiOutput('restored_ui'), #this is very important
bookmarkButton())
# Server logic
server <- function(input, output, session) {
counter <- reactiveValues()
counter$n <- c(0) #This value is only used to initialize the object.
total_ui_count <- reactiveValues()
total_ui_count$info <- 0 #because input$add will reset to zero this will count the number of uis to remember.
#When bookmark button is pressed
onBookmark(function(state) {
state$values$currentCounter <- counter$n
state$values$input_restore <- reactiveValuesToList(input)
print(names(input) %>% str_subset('^txt'))
state$values$total_uis_to_restore <- counter$n[[length(counter$n)]]
})
#rerender the previous outputs and their values
onRestore(function(state) {
#restore values from previous state
counter$n <- state$values$currentCounter
vals <- state$values$input_restore
print(str_subset(names(vals), '^txt.*$')) #for debugging
total_ui_count$info <- state$values$total_uis_to_restore
print(total_ui_count$info)
#render back a ui with the previous values.
output$restored_ui <- renderUI({
str_subset(names(vals), '^txt.*$') %>%
sort(decreasing = TRUE) %>% #to avoid order reversal of the inputs
map(~ textInput(.x, label = .x, value = vals[[.x]])) #render the last inputs
})
})
observeEvent(input$add, {
#input$add starts as 1 in the next state (because ui is not wrapped in function(request)) that's why total_ui_count is present
counter$n <- c(counter$n, input$add + total_ui_count$info)
print(counter$n) #for debugging
insertUI(
selector = "#add",
where = "afterEnd",
ui = textInput(inputId = paste0("txt", counter$n[[length(counter$n)]]),
label = "Insert some text")
)})
}
# Complete app with UI and server components
shinyApp(ui, server, enableBookmarking = "server")

Prevent Select Input From Resetting With Streaming Data Updates

I am trying to come up with a way to prevent a select input from resetting when the data it depends upon changes. Ideally, as more data arrives, the choices expand, silently, without visual disruption or input value resetting. I've tried using updateSelectInput, but without success. I've created an example that reasonably approximates my problem, have left in my comments and ideas to show where I tried to come up with a solution, and am hoping someone else has a better idea they can share. As always, thank you in advance. -nate
library(shiny)
if (interactive()) {
ui <- fluidPage(
titlePanel("Is It Possible To Prevent The Select Input From Resetting with New Data Arriving?"),
sidebarLayout(
sidebarPanel(
shiny::uiOutput(outputId = "streaming_select")
),
mainPanel(
tableOutput("table")
)
)
)
server<- function(input, output, session){
session_launched<- reactiveValues(count=1)
fake_global_rv_list<- reactiveValues()
fake_global_rv_list$tmp<- data.frame(glob_0001=runif(10))
session_rv_list<- reactiveValues()
session_rv_list$tmp<- data.frame(sess_0001=runif(10))
# Simulating Streaming Data every 7 seconds
shiny::observe({
shiny::invalidateLater(millis = 7000)
shiny::isolate({
shiny::showNotification(ui = "Generating Random Data", type = "default", duration = 3)
tmp<- data.frame(runif(10) )
colnames(tmp)<- paste0("stream_",format(as.numeric(Sys.time())))
session_rv_list$tmp<- cbind(session_rv_list$tmp, tmp) # Put the random data into the reactive Values list
})
})
full_dat<- shiny::reactive({ cbind(fake_global_rv_list$tmp, session_rv_list$tmp) })
# Table of 'Streaming' Data
output$table <- renderTable({
full_dat()
})
## Select Input that let's you pick a single column
output$streaming_select<- shiny::renderUI({
if(!is.null(full_dat())){
if(session_launched$count==1){
out<- shiny::selectizeInput(inputId = "streaming_select_input", label="Pick A Column", choices = unique(colnames(full_dat())), selected = NULL, multiple = TRUE)
}
}
})
## Possible Ideas (?) BELOW
# select_choices<- shiny::eventReactive(full_dat(), {
# if(!is.null(full_dat())){
# if(session_launched$count==1){
# out<- list( choices = unique(colnames(full_dat())), selected = NULL)
# #shiny::selectizeInput(inputId = "streaming_select_input", label="Pick A Column", choices = unique(colnames(full_dat())), selected = NULL, multiple = TRUE)
# session_launched$count<- 2
# return(out)
# } else if(session_launched$count > 1){
# old_selections<- input$streaming_select_input
# out<- list( choices = unique(colnames(full_dat())), selected = old_selections)
# return(out)
# #shiny::updateSelectizeInput(session, inputId = "streaming_select_input", choices = unique(colnames(full_dat())), selected = old_selections)
# }
# }
# })
# observeEvent(select_choices(), {
# cat("STR of select_choices is...", "\n")
# cat(str(select_choices()), "\n")
# })
#
# shiny::observeEvent(full_dat(), {
# if(session_launched$count != 1){
# old_selections<- input$streaming_select_input
# shiny::updateSelectizeInput(session, inputId = "streaming_select_input", choices = unique(colnames(full_dat())), selected = old_selections)
# }
# })
}
shinyApp(ui, server)
}
Below is an example that works. I create the selectizeInput in the ui part, and update it on change of the full_dat data frame using an observeEvent. I had to store and reset the selection in this update step to prevent it from being set to NULL.
library(shiny)
if (interactive()) {
ui <- fluidPage(
titlePanel("Is It Possible To Prevent The Select Input From Resetting with New Data Arriving?"),
sidebarLayout(
sidebarPanel(
shiny::selectizeInput(inputId = "streaming_select_input", label="Pick A Column",
choices = NULL,
selected = NULL,
multiple = TRUE)
),
mainPanel(
tableOutput("table")
)
)
)
server<- function(input, output, session){
session_launched<- reactiveValues(count=1)
fake_global_rv_list<- reactiveValues()
fake_global_rv_list$tmp<- data.frame(glob_0001=runif(10))
session_rv_list<- reactiveValues()
session_rv_list$tmp<- data.frame(sess_0001=runif(10))
# Simulating Streaming Data every 7 seconds
shiny::observe({
shiny::invalidateLater(millis = 7000)
shiny::isolate({
shiny::showNotification(ui = "Generating Random Data", type = "default", duration = 3)
tmp<- data.frame(runif(10) )
colnames(tmp)<- paste0("stream_",format(as.numeric(Sys.time())))
session_rv_list$tmp<- cbind(session_rv_list$tmp, tmp) # Put the random data into the reactive Values list
})
})
full_dat<- shiny::reactive({ cbind(fake_global_rv_list$tmp, session_rv_list$tmp) })
# Table of 'Streaming' Data
output$table <- renderTable({
full_dat()
})
## Select Input that let's you pick a single column
observeEvent(full_dat(), {
selectedCols <- input$streaming_select_input
updateSelectizeInput(session, "streaming_select_input", choices = colnames(full_dat()), selected = selectedCols)
})
}
shinyApp(ui, server)
}

use rhandsontable package to edit multiple data frame on shiny

I am new to the shiny, I would like to edit different multiple data frames by radio button or selectinput by using rhandsontable package. However, my script can not show other data frame but only the first one, I don't know what is the problem.
ui.R:
library(rhandsontable)
fluidPage(
sidebarLayout(
sidebarPanel(
selectInput("select2", label = h3("Choose to edit"),
choices = list("003.csv", "004.csv", "005.csv",
"006.csv", "007.csv"),
selected = "003.csv"),
actionButton("saveBtn", "Save changes")
),
mainPanel(
rHandsontableOutput("hot")
)))
server.R
values <- reactiveValues()
setHot <- function(x) values[["hot"]] <<- x
function(input, output, session) {
fname <- reactive({
x <- input$select2
return(x)
})
observe({
input$saveBtn # update csv file each time the button is pressed
if (!is.null(values[["hot"]])) {
write.csv(x = values[["hot"]], file = fname(), row.names = FALSE)
}
})
output$hot <- renderRHandsontable({
if (!is.null(input$hot)) { # if there is an rhot user input...
DF <- hot_to_r(input$hot) # convert rhandsontable data to R object
and store in data frame
setHot(DF) # set the rhandsontable values
} else {
DF <- read.csv(fname(), stringsAsFactors = FALSE) # else pull table from the csv (default)
setHot(DF) # set the rhandsontable values
}
rhandsontable(DF) %>% # actual rhandsontable object
hot_table(highlightCol = TRUE, highlightRow = TRUE, readOnly = TRUE) %>%
hot_col("Status", readOnly = FALSE)
})}
I can edit and save the dataframe that it shows the first one 003.csv, however when i use the drop down list to 004.csv, it didn't show the dataframe. please advise.
This will write (and possibly overwrite ⚠ any existing file with) dummy data:
for (i in c("003.csv", "004.csv", "005.csv", "006.csv", "007.csv")) {
write.csv(cbind(V1 = rep(i, 3), Status = "foo"), i, row.names = FALSE)
}
I overhauled server a bit:
library(shiny)
library(rhandsontable)
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
selectInput(
"select2", label = h3("Choose to edit"), selected = "003.csv",
choices = list("003.csv", "004.csv", "005.csv", "006.csv", "007.csv")
),
actionButton("saveBtn", "Save changes")
),
mainPanel(
rHandsontableOutput("hot")
)
)
)
server <- function(input, output, session) {
DF <- reactiveVal()
observe({
DF(read.csv(input$select2, stringsAsFactors = FALSE))
})
observe({
if (!is.null(input$hot)) DF(hot_to_r(input$hot))
})
observeEvent(input$saveBtn, {
if (!is.null(DF())) write.csv(DF(), input$select2, row.names = FALSE)
})
output$hot <- renderRHandsontable({
rhandsontable(DF()) %>%
hot_table(highlightCol = TRUE, highlightRow = TRUE, readOnly = TRUE) %>%
hot_col("Status", readOnly = FALSE)
})
}
shinyApp(ui, server)

Shiny R: Modifying the variable class

I am trying to create a shiny-app that load data-set, present the variable list and their classes and allow the user to modify the class of a selected variable. All the functions in the following code are working except to the last function in the server- observeEvent which not working when trying to modify the variable class. Any suggestions?
Thank you in advance,
Rami
`
rm(list = ls())
library(shiny)
library(shinydashboard)
library(DT)
ui <- dashboardPage(
dashboardHeader(title = "Shiny Example"),
#--------------------------------------------------------------------
dashboardSidebar(
sidebarMenu(
menuItem("Data", tabName = "data", icon = icon("th"))
)
),
#--------------------------------------------------------------------
dashboardBody(
#--------------------------------------------------------------------
tabItem(tabName = "data",
fluidPage(
fluidRow(
box(
selectInput('dataset', 'Select Dataset', list(GermanCredit = "GermanCredit",
cars = "cars",
iris = "iris")),
title = "Datasets",width = 4, status = "primary",
checkboxInput("select_all", "Select All Variable", value = TRUE),
conditionalPanel(condition = "input.select_all == false",
uiOutput("show.var"))
),
box(
title = "Variable Summary", width = 4, status = "primary",
DT::dataTableOutput('summary.data')
),
box(
title = "Modify the Variable Class", width = 4, status = "primary",
radioButtons("choose_class", label = "Modify the Variable Class",
choices = list(Numeric = "numeric", Factor = "factor",
Character = "character"),
selected = "numeric"),
actionButton("var_modify", "Modify")
)
)
)
)
)
)
#--------------------------------------------------------------------
# Server Function
#--------------------------------------------------------------------
server <- function(input, output,session) {
#--------------------------------------------------------------------
# loading the data
get.df <- reactive({
if(input$dataset == "GermanCredit"){
data("GermanCredit")
GermanCredit
}else if(input$dataset == "cars"){
data(cars)
cars
}else if(input$dataset == "iris"){
data("iris")
iris
}
})
# Getting the list of variable from the loaded dataset
var_list <- reactive(names(get.df()))
# Choosing the variable - checkbox option
output$show.var <- renderUI({
checkboxGroupInput('show_var', 'Select Variables', var_list(), selected = var_list())
})
# Setting the data frame based on the variable selction
df <- reactive({
if(input$select_all){
df <- get.df()
} else if(!input$select_all){
df <- get.df()[, input$show_var, drop = FALSE]
}
return(df)
})
# create list of variables
col.name <- reactive({
d <- data.frame(names(df()), sapply(df(),class))
names(d) <- c("Name", "Class")
return(d)
})
# render the variable list into table
output$summary.data <- DT::renderDataTable(col.name(), server = FALSE, rownames = FALSE,
selection = list(selected = 1, mode = 'single'),
options = list(lengthMenu = c(5, 10, 15, 20), pageLength = 20, dom = 'p'))
# storing the selected variable from the variables list table
table.sel <- reactive({
df()[,which(colnames(df()) == col.name()[input$summary.data_rows_selected,1])]
})
# Trying to modify the variable class
observeEvent(input$var_modify,{
modify.row <- which(colnames(df()) == col.name()[input$summary.data_rows_selected,1])
if( input$choose_class == "numeric"){
df()[, modify.row] <- as.numeric(df()[, modify.row])
} else if( input$choose_class == "factor"){
df()[, modify.row] <- as.factor(df()[, modify.row])
} else if( input$choose_class == "character"){
df()[, modify.row] <- as.character(df()[, modify.row])
}
})
}
shinyApp(ui = ui, server = server)
`
I would use reactiveValues() instead.
library(shiny)
# Define UI for application that draws a histogram
ui <- shinyUI(fluidPage(
sidebarLayout(
sidebarPanel(
selectInput("classType", "Class Type:", c("as.numeric", "as.character"))
),
mainPanel(
textOutput("class")
)
)
))
server <- shinyServer(function(input, output) {
global <- reactiveValues(sample = 1:9)
observe({
global$sample <- get(input$classType)(global$sample)
})
output$class <- renderText({
print(class(global$sample))
})
})
shinyApp(ui = ui, server = server)
In case you are interested:
Concerning your attempt: reactive() is a function and you called the output of the function by df()[, modify.row]. So in your code you try to change the output of the function, but that does not change the output of futures calls of that function.
Maybe it is easier to see in a simplified version:
mean(1:3) <- 1
The code can not change the mean function to output 1 in future. So thats what reactiveValues() help with :). Hope that helps!

Resources