In the below toy example I have a data set datapred. The data set are output to an interactive table using rhandsontable. Then I covert it in a new data.frame with hot_to_r. My issue is that when I wnat to use it in my function prediction(), it send me an error message and the application crash. I don't understand why.
I'm french so I converted in english the message :
Error in as.name: the 'pairlist' object can not be automatically converted to a 'symbol' type.
library(shiny)
library(frailtypack)
library(rhandsontable)
data("readmission", package = "frailtypack")
ui <- fluidPage(
titlePanel("prediction"),
mainPanel(
fluidRow(rHandsontableOutput("hot")),
br(),
plotOutput("pred")
)
)
server <- function(input, output) {
newdata <- subset(readmission,select = c("time","event","id","dukes"))
datapred <- newdata[1,]
data <- reactive({
DF = hot_to_r(input$hot)
DF
})
model <- frailtyPenal(Surv(time,event)~cluster(id)+dukes,n.knots=10,
kappa=10000,data=readmission)
predict <- reactive(
prediction(model, data(),t=200,window=seq(50,1900,50),
MC.sample=100))
output$hot <- renderRHandsontable({
rhandsontable(datapred)
})
data <- reactive({
DF = hot_to_r(input$hot)
DF
})
output$pred <- renderPlot({
plot(predict(),conf.bands=TRUE)
})
}
shinyApp(ui = ui, server = server)
You could simply evaluate the data() first, like this. I also added some checks so you don't get other errors during the initialization
library(shiny)
library(frailtypack)
library(rhandsontable)
data("readmission", package = "frailtypack")
ui <- fluidPage(
titlePanel("prediction"),
mainPanel(
fluidRow(rHandsontableOutput("hot")),
br(),
plotOutput("pred")
)
)
server <- function(input, output) {
newdata <- subset(readmission,select = c("time","event","id","dukes"))
datapred <- newdata[1,]
data <- reactive({
hot <- input$hot
if (!is.null(hot)) hot_to_r(hot)
})
model <- frailtyPenal(Surv(time,event)~cluster(id)+dukes,n.knots=10,
kappa=10000,data=readmission)
predict <- reactive({
dat <- data()
if (!is.null(dat)) {
prediction(model, dat,t=200,window=seq(50,1900,50),
MC.sample=100)
}
})
output$hot <- renderRHandsontable({
rhandsontable(datapred)
})
output$pred <- renderPlot({
pred <- predict()
if (!is.null(pred)) plot(pred, conf.bands = TRUE)
})
}
shinyApp(ui = ui, server = server)
Related
I would like to have a shiny app that, when run for the first time, displays a dataframe defined as a template, and then the user can upload a new one (in csv only) that replaces the current one. Therefore, in case the user imports a file of the wrong type, it produces a message instead. Here is my code, which results in an error, and I don't know why it doesn't work
library(shiny)
library(DT)
library(dplyr)
library(shiny)
ui <- fluidPage(
fileInput("upload", NULL, accept = c(".csv")),
tableOutput("head")
)
server <- function(input, output, session) {
rv <- reactiveValues(
dataframe = NULL
)
observe({
if(is.null(rv$dataframe)){
dataFrameFile <- reactive({
df <- data.frame(
x = seq(1:12),
y = rnorm(12))
rv$dataframe <- datatable(df)
return(rv$dataframe)
})
} else {
dataFrameFile <- reactive({
req(input$upload)
ext <- tools::file_ext(input$upload$name)
rv$dataframe <- switch(ext,
csv = read.csv(input$upload$datapath),
validate(" Please upload a .csv file")
)
})
}
})
output$head <- renderDT({
datatable(dataFrameFile())
})
}
shinyApp(ui, server)
A few corrections/simplifications:
Used DTOutput instead of tableOutput to correspond to renderDT
directly initialized rv
put the validate in the renderDT
library(shiny)
library(DT)
library(dplyr)
library(shiny)
ui <- fluidPage(
fileInput("upload", NULL, accept = c(".csv")),
DTOutput("head")
)
server <- function(input, output, session) {
rv <- reactiveValues(
dataframe = data.frame(
x = seq(1:12),
y = rnorm(12))
)
observe({
req(input$upload)
ext <- tools::file_ext(input$upload$name)
rv$dataframe <- switch(ext,
csv = read.csv(input$upload$datapath),
NULL)
})
output$head <- renderDT({
validate(need(!is.null(rv$dataframe)," Please upload a .csv file"))
rv$dataframe
})
}
shinyApp(ui, server)
I am trying to put this code in Shiny with dynamic dates and ticker selection, but I get the following error Operation not allowed without an active reactive context.
You tried to do something that can only be done from inside a reactive consumer.
library(quantmod)
library(PerformanceAnalytics)
dt <- "2017-2-1"
aapl <- getSymbols.yahoo("AAPL", from=dt, auto.assign = F)
aaplClose <- getSymbols.yahoo("AAPL", from=dt, auto.assign = F)[,6]
aaplRets <- na.omit(dailyReturn(aaplClose, type="log"))
Here is my shiny implementation
library(shiny)
library(quantmod)
library(PerformanceAnalytics)
#dt <- "2017-2-1"
ui <- fluidPage(
dateInput("dt", "Select a date:"),
textInput("tkr", "Enter a ticker symbol"),
plotOutput("myplot")
)
server <- function(input, output, session) {
aapl <- reactive ({
getSymbols.yahoo(input$tkr, from=input$dt, auto.assign = F)
})
aaplClose <- reactive ({
getSymbols.yahoo(input$tkr, from=input$dt, auto.assign = F)[,6]
})
aaplRets <- na.omit(dailyReturn(aaplClose(), type="log"))
output$myplot <- renderPlot(
{ chartSeries(aapl())}
)
}
shinyApp(ui, server)
Since you have a text input to select the ticker, the data should not be called apple, because it can be everything. Keeping everything in reactive contextes:
library(shiny)
library(quantmod)
library(PerformanceAnalytics)
ui <- fluidPage(
dateInput("dt", "Select a date:", value = "2017-2-1"),
textInput("tkr", "Enter a ticker symbol", value = "AAPL"),
plotOutput("myplot")
)
server <- function(input, output, session) {
data <- reactive({
getSymbols.yahoo(input$tkr, from = input$dt, auto.assign = F)
})
output$myplot <- renderPlot({
chartSeries(data())
})
}
shinyApp(ui, server)
Or with Alphabet:
I am building a Shiny app and using the code from this question as an example: How to download editable data table in shiny. However, in my code the df <- reactiveVal(dat) does not work, because the dat itself is already a reactive value that comes from an eventReactive({}) function. This is the code I am working with, it works if I define the dat outside of the server, but not when it is created inside the server function of shiny. How do I make a copy of it so that I can show it in a new table (and potentially process further and download in later steps in the app)?
library(shiny)
library(DT)
library(shinyWidgets)
# if the data frame is just an object, it works
#dat <- iris[1:3, ]
ui <- fluidPage( actionBttn(
inputId = "btnProcess",
label = "Process",
size = "sm",
color = "success"
),
DTOutput("my_table"),
DTOutput("table2")
)
server <- function(input, output){
# if the dataframe is a reactive variable, this doesnt work.
dat <- eventReactive(input$btnProcess, {
iris[1:3, ]
})
output[["my_table"]] <- renderDT({
datatable(dat(), editable = "cell")
})
#############################
#### none of these work #####
#############################
#df <- reactiveVal(dat)
#df <- reactiveVal(dat())
#df <- dat()
#df <- dat
observeEvent(input[["my_table_cell_edit"]], {
cell <- input[["my_table_cell_edit"]]
newdf <- df()
newdf[cell$row, cell$col] <- cell$value
df(newdf)
})
output[["table2"]] <- renderDT({
datatable(df())
})
}
shinyApp(ui, server)
Try this
ui <- fluidPage( actionBttn(
inputId = "btnProcess",
label = "Process",
size = "sm",
color = "success"
),
actionBttn(inputId = "reset", label = "Reset", size="sm", color="warning"),
DTOutput("mytable"),
DTOutput("table2")
)
server <- function(input, output){
# if the dataframe is a reactive variable, this doesnt work.
dat <- eventReactive(input$btnProcess, {
iris[1:3, ]
})
mydf <- reactiveValues(data=NULL)
observe({
mydf$data <- dat()
})
output$mytable <- renderDT({
datatable(mydf$data, editable = "cell")
})
observeEvent(input$mytable_cell_edit, {
info = input$mytable_cell_edit
str(info)
i = info$row
j = info$col
v = info$value
mydf$data[i, j] <<- DT::coerceValue(v, mydf$data[i, j])
})
output[["table2"]] <- renderDT({
datatable(mydf$data)
})
observeEvent(input$reset, {
mydf$data <- dat() ## reset it to original data
})
}
shinyApp(ui, server)
I am trying to build an app in shiny that will be able to load a dataset in the server function and then based on the user choose and then if there is a factor variable to open check box using conditionalPanel. is there a way to output variable from the server as the condition of the condtionalPanel?
Here is what I tried:
library(shiny)
library(caret)
ui <- fluidPage(
selectInput('dataset', 'Select Dataset',
list(GermanCredit = "GermanCredit",
cars = "cars")),
conditionalPanel(
condition = "output.factorflag == true",
checkboxInput("UseFactor", "Add Factor Variable")
)
)
server <- function(input, output) {
# Loading the dataset
df <- reactive({
if(input$dataset == "GermanCredit"){
data("GermanCredit")
df <- GermanCredit
}else if(input$dataset == "cars"){
data(cars)
df <- cars
}
return(df)
})
# Loading the variables list
col_type <- reactive({
col_type <- rep(NA,ncol(df()))
for(i in 1:ncol(df())){
col_type[i] <- class(df()[,i])
}
return(col_type)
})
outputOptions(output, "factorflag", suspendWhenHidden = FALSE)
output$factorflag <- reactive({
if("factor" %in% col_type()){
factor.flag <- TRUE
} else {factor.flag <- FALSE}
}
)
}
shinyApp(ui = ui, server = server)
Thank you in advance!
You were almost there, you need to put the outputOptions after the declaration of factorflag. Just reengineered a bit your code:
library(shiny)
library(caret)
ui <- fluidPage(
selectInput('dataset', 'Select Dataset',
list(GermanCredit = "GermanCredit",
cars = "cars")),
conditionalPanel(
condition = "output.factorflag == true",
checkboxInput("UseFactor", "Add Factor Variable")
)
)
server <- function(input, output) {
# Loading the dataset
df <- reactive({
if(input$dataset == "GermanCredit"){
data("GermanCredit")
GermanCredit
}else {
data("cars")
cars
}
})
output$factorflag <- reactive("factor" %in% sapply(df(),class))
outputOptions(output, "factorflag", suspendWhenHidden = FALSE)
}
shinyApp(ui = ui, server = server)
I've had some luck with Shiny and R, but I can't get an selectInput function to change the dataframe. I'm probably missing something obvious, but here's my code
require(shiny)
A <- data.frame(x=c(1,2,3),y=c(3,2,1))
B <- data.frame(x=c(1,1,5),y=c(3,5,0))
ui <- fluidPage(
selectInput("df", "Select dataframe", choices = c('A'='A','B'='B'), selected = 'A'),
plotOutput("Plot")
)
server <- function(input, output)
{
df <- reactive({
x <- as.data.frame(input$df)
})
output$Plot <- renderPlot({
df <- df()
plot(x=df$x, y=df$y)
})
}
shinyApp(ui = ui, server = server)
What am I missing?
You cant use as.data.frame and name of df
try to use get
A <- data.frame(x=c(1,2,3),y=c(3,2,1))
B <- data.frame(x=c(1,1,5),y=c(3,5,0))
shinyServer(function(input, output) {
df <- reactive({
x <- get(input$df)
})
output$Plot <- renderPlot({
df <- df()
plot(x=df$x, y=df$y)
})
})