How can I display time series graph with its forecasting line? - r

The object is gettig parameters from users to make them understand the forecasting techniques. Therefore, i would like to begin with moving average. Eventhough the work is quite simple, i couldnt manage and i have some issues.
One error occurs: ERROR: missing value where TRUE/FALSE needed.
I do not understand why do I get this?
I want to show forecasted values for next period. But with this ready formula does not provide that?
`
library(shiny)
shinyUI(pageWithSidebar(
headerPanel("Forecasting Methods"),
sidebarPanel(
h3(strong("Moving Average",style = "color:black")),
br(),
sliderInput("ord","Order Size:",min = 1, max = 100, step= 1, value = 15),
),
mainPanel(
plotOutput(outputId = "ma1", width = "700px",height = "400px"))
))
library(shiny)
library(ggplot2)
library(forecast)
library(TTR)
shinyServer(function(input, output){
output$ma1 <- renderPlot(
tmp <- data.frame(time = 1:100, sales = round(runif(100, 150, 879))),
sm <- SMA(tmp[,"sales"],order=input$ord),
y <-ggplot(tmp, aes(time, sales)) + geom_line() + geom_line(aes(time,sm),color="red") + xlab("Days") + ylab("Sales Quantity")+ ggtitle("Moving Average"),
y
)
})

How is this:
library(shiny)
library(ggplot2)
library(forecast)
library(TTR)
ui <- pageWithSidebar(
headerPanel("Forecasting Methods"),
sidebarPanel(
h3(strong("Moving Average",style = "color:black")),
br(),
sliderInput("ord","Order Size:",min = 1, max = 100, step= 1, value = 15)
),
mainPanel(
plotOutput(outputId = "ma1", width = "700px",height = "400px"))
)
server <- function(input, output){
n <- 0
output$ma1 <- renderPlot({
input$ord
tmp <- data.frame(time = 1:100, sales = round(runif(100, 150, 879)) )
sm <- SMA(tmp[,"sales"],order=input$ord)
title <- sprintf("Moving Average (%d)",n)
n <<- n+1
y <-ggplot(tmp, aes(time, sales)) +
geom_line() +
geom_line(aes(time,sm),color="red") +
xlab("Days") + ylab("Sales Quantity")+ ggtitle(title)
y
})
}
shinyApp(ui, server)
Yielding:
As to your program - I could not reproduce your errors exactly:
1 - the program as posted would not run. The server function code block was not enclosed in curly brackets ({}), but was structured like the ui function code (comma separated statements). This is wrong. The ui function code not a function like the server code, rather it series of function calls that output html/css/javascript. Try them from the R-console to see what I mean.
2 - the UI function had at least one extraneous comma that I had to get rid of in order for it to work.
3 - using input$ord in the output$ma1 code that initializes the sm dataframe was not enough to cause the function to be reactive, and be triggered on every update of the slider. Not sure why that was not enough, but when I added another instance of input$ord to the front of the function it worked.
4- I also put a counter in the title of the output$ma1 to help me debug the above-debugged lack of reactivity.
5 - I also combined both the shiny ui.R and server.R files into one file as this example is small and makes it easy to see everything at once. Note that it can be hard matching ui.R and server.R code with the Rstudio tabbed editor - it is worth getting another editor (like Atom or Notepad++) to help code if you need more than one file.

Related

how to design a reactive visualization graph for a time series using shiny?

I want to design a reactive interaction graph for a time series for shiny.
It is used for when I have a time series. I change the first point of the time series.
Then I can get the reactive graph changed for the point changed.
I have trouble for how to assign the value input into the function. Specifically, for the
yinput<-sensi(num). I want to the input be some number range from 0.1 to 0.9.but my sensitive's
function only allow to enter one input.
Is there any idea for that?
Thanks
library(ggplot2)
sensi<-function(input)
{
y<-c(input,5,12,21,30,50,90,100)
return(y)
}
Date = c("2020/07/16","2020/07/23","2020/07/30","2020/08/06","2020/08/13","2020/08/20","2020/08/27","2020/09/13")
num<-c(0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9)
yinput<-sensi(num)
df <- data.frame(yinput, Date = as.Date(Date))
ui <- fluidPage(
titlePanel(title=h4("plot1", align="center")),
sidebarPanel(
sliderInput("num", "Number:",min = 0, max = 0.9,value=0.5)),
mainPanel(plotOutput("plot2")))
server <- function(input,output){
dat <- reactive({
test <- df[df$num %in% seq(from=min(input$num),to=max(input$num),by=1),]
print(test)
test
})
output$plot2<-renderPlot({
ggplot(df) + aes(Date, y) + geom_line()})}
shinyApp(ui, server)
Here's a very basic example
You should be doing your 'thinking' inside your 'server' function.
Hopefully this example will show you how reactive inputs and outputs relate to each other, and you can extend it to your plot.
require(shiny)
ui <- fluidPage(
sliderInput("num", "Number:", min = 0.1, max = 0.9, value = 0.5),
textOutput("number_display")
)
server <- function(input, output){
output$number_display <-
renderText({
as.character(input$num)
})
}
shinyApp(ui = ui, server = server)
Where I've said as.character(input$num), you'll want to do something with num to make your plot.

R Shiny not plotting at all

I'm new to shiny and I'm trying to use it for a simulation of a prey/predator model.
First, I wanted to generate the dataframe with all the initial positions for each animal; and try to plot it usign ggplot; but when I hit the actionButton, the plot never showed. I dont interstand why and there is any error message to let me at least know what is wrong.
Here is the code:
library(shiny)
library(tidyverse)
library(ggplot2)
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
sliderInput("nPrey", "select total number of preys", 1, 100, 10, 1),
sliderInput("nHunter", "select total number of Hunters", 1, 100, 10, 1),
actionButton ("play", "Begin simulation")
),
mainPanel(
plotOutput("plot")
)
)
)
server <- function(input, output, session) {
zMax = 20
simulation <- eventReactive(input$play, {
createInitialTable(input$nPrey, input$nHunter)
})
output$plot <- renderPlot({
p <- ggplot() +
geom_point(aes_string(x="X",y="Y"), data=simulation()) +
coord_cartesian(xlim =c(0, zMax), ylim = c(0, zMax))
})
createInitialTable <- function (nPrey, nHunter){
aAnimal <- data.frame()
cVar <- c("X", "Y")
for (i in 1:nPrey){
aAnimal <- rbind(aAnimal, c(round(runif(1)*zMax), round(runif(1)*zMax)))
}
for (i in 1:nHunter){
aAnimal <- rbind(aAnimal, c(round(runif(1)*zMax), round(runif(1)*zMax)))
}
colnames(aAnimal) <- cVar
return (aAnimal)
}
}
shinyApp(ui, server)
Thank you for reading this
Simple fix: Remove p <- and you should be good to go. However, to improve you need to check the reactivity of your execution when the nPrey and Hunter are dynamically changing.

non-numeric argument to binary operator in shiny app

This is my code below, I think it may just be a silly mistake but I have spent the last 5 days trying to find where I went wrong in my app:-
ui <- fluidPage(h1("Left Ventricular Hypertrophy"),
titlePanel("Regression Model"),
sidebarLayout(
sidebarPanel(
h3("Marginal Histogram"),
selectInput("marhis1", "X:", choices = unique(colnames(lvh))),
selectInput("marhis2", "Y:", choices = unique(colnames(lvh)), selected = "sbp"),
sliderInput("bin", "Bin Width:", min = 1, max = 100, value = 10),
h3("Box Plot"),
selectInput("Variable4", "llvmi or sbp:", choices = c("llvmi", "sbp")),
selectInput("Variable5", "Grouped by:", choices = c("sex", "card", "dgp", "surv")),
mainPanel(
h3("Marginal Histogram"),
plotOutput("hist"),
br(),
h3("Boxplot"),
plotOutput("Box")
)
)
)
server <- function(input, output) {
lvh <- read.table('lvh.dat.txt', header = T)
output$hist <- renderPlot({
marg <- ggplot(lvh, aes(input$marhis1, input$marhis2) + geom_point() + theme_light() +
xlab(input$marhis1) + ylab(input$marhis2))
ggMarginal(marg, input$marhis1, input$marhis2, type = "histogram", binwidth = input$bin)
})
output$Box <- renderPlot({
choice2 <- data.frame(x=lvh[input$Variable4], y=lvh[input$Variable5])
ggplot(choice2, aes(lvh[input$Variable4], lvh[input$Variable5]) + geom_boxplot() + theme_light() +
xlab(input$Variable4) + ylab(input$Variable5))
})
}
shinyApp(ui = ui, server = server)
I keep getting an error of non-numeric argument to binary operator in both of the plots when I run app, could anyone help
First, let me encourage you to always provide code samples that are easy to inspect. Since, from your comment conversation in the original post, one can see that you did not quite get what that means: Make the code snippet so that simple copy + paste will be enough to run into the errors you are facing.
At least four people looked at your code and everyone was immediately discouraged to invest some patience into it.
Otherwise it would have been easy to detect, that you are just missing a parenthesis in the part
ggplot(lvh, aes(input$marhis1, input$marhis2) + geom_point()
where it must be
ggplot(lvh, aes(input$marhis1, input$marhis2)) + geom_point()
(of course eliminating the also misplaced original closing bracket).
Edit: Same goes for the second call to ggplot. More on that: ggplot works by adding layers to the plot. That is why you have to add (+) the ggplot(...) generated elements. Not adding options inside the call to ggplot.

How to sliderInput for Dates

This is causing me a lot of pain.
I would like to simlpy have a sliderInput that takes a Date (preferably stepping by month) and changes a simple ggplot_bar as a result. Although I can show everything there seems to be no response to the changing of the slider:
Here is my code:
ui.r
library(shiny)
# Define UI for application that draws a histogram
shinyUI(fluidPage(
# Application title
titlePanel("St Thomas' Physiology Data Console"),
# Sidebar with a slider input for the number of bins
sidebarLayout(
sidebarPanel(
sliderInput("DatesMerge",
"Dates:",
min = as.Date("2006-01-01","%Y-%m-%d"),
max = as.Date("2016-12-01","%Y-%m-%d"),
value=as.Date("2016-12-01"),timeFormat="%Y-%m-%d")
),
# Show a plot of the generated distribution
mainPanel(
tabsetPanel(
tabPanel("Breath Tests",plotOutput("distPlotLactul")),
)
)
))
server.r
library(shiny)
source("S:\\Usage.R")
# Define server logic required to draw a histogram
shinyServer(function(input, output) {
output$distPlotLactul <- renderPlot({
#Create the data
DatesMerge<-input$DatesMerge
# draw the histogram with the specified number of bins
ggplot(TotsLactul)+
geom_bar(aes(DatesMerge,fill=year))+
labs(title=paste("Num")) +
xlab("Time") +
ylab("NumP") +
theme(axis.text.x=element_text(angle=-90)) +
theme(legend.position="top")+
theme(axis.text=element_text(size=6))
})
})
I wasn't totally sure of your ggplot code, so I had to rejig into something I understood.
I also created my own data to make it reproducible.
Here is the data I made
# Generate random variates
TotsLactul <- rep(ymd("2016-01-01"),10000)
randomMonths <- round(runif(n = 10000,min = 0,max = 11),0)
randomDays <- round(runif(n = 10000,min = 0,max = 28),0)
# Increments days
month(TotsLactul) <- month(TotsLactul) + randomMonths
day(TotsLactul) <- day(TotsLactul) + randomDays
# Make it a DT
TotsLactul <- data.table(x=TotsLactul)
This is just random dates throughout the year.
UI
ui <- shinyUI(fluidPage(
# Application title
titlePanel("St Thomas' Physiology Data Console"),
# Sidebar with a slider input for the number of bins
sidebarLayout(
sidebarPanel(
sliderInput("DatesMerge",
"Dates:",
min = as.Date("2016-01-01","%Y-%m-%d"),
max = as.Date("2016-12-01","%Y-%m-%d"),
value=as.Date("2016-12-01"),
timeFormat="%Y-%m-%d")
),
mainPanel(
plotOutput("distPlotLactul"))
)
))
I amended the slider to only take 2016 values, to match my generated data
Server
server <- shinyServer(function(input, output) {
output$distPlotLactul <- renderPlot({
#Create the data
DatesMerge<-input$DatesMerge
# draw the histogram with the specified number of bins
ggplot(TotsLactul[month(x) == month(DatesMerge)],mapping=aes(x=x))+
geom_histogram(bins=100)+
labs(title=paste("Num")) +
xlab("Time") +
ylab("NumP") +
theme(axis.text.x=element_text(angle=-90)) +
theme(legend.position="top")+
theme(axis.text=element_text(size=6))
})
})
I'll be honest, I have never used ggplot like you have (just dropped in a table in a geom etc.), so I can't comment on if any of it was right / wrong. Hopefully you can follow my changes.
Changed geom_bar to geom_hist (to match my data)
The filtering happens in the data included in the plot, not within the geom.
This seems to work fine, let me know how you get on.

R, Shiny, plotting a reactive data frame (data goes "missing")

Given the following ui.R and server.R and circuit.csv; I can produce a simple plot which reacts to the user input (power in this case).
However, not all values for power are returned. For example, .5 produces a plot whereas .6 does not, so on and so forth at random occurrence throughout the power range.
If i plot as a table instead, to check my work, same thing, certain power inputs work as expected and others produce no table, and also no plot when asking to plot.
ui.R
library(shiny)
library(ggplot2)
shinyUI(fluidPage(
hr(),
sidebarLayout(
sidebarPanel(
sliderInput("power",label = "Power",
min = 0, max = 5, value = .5, step = .1)
),
mainPanel(
p("Lum vs Distance by Power"),
plotOutput('plot1')
)
)
))
server.R
library(shiny)
library(ggplot2)
df <- read.table(file = "circuit.csv", sep=",", header = TRUE)
shinyServer(function(input, output) {
output$plot1 <- renderPlot({
df2 <- subset(df,df$pow==input$power)
p <- ggplot(df2)+
geom_point(aes(x=dist, y=lum))
print(p)
})
})
Link to github (for csv data)
I would post images but am not allowed to do so at this time.

Resources