I have a question which may be stupid, but I just wanted to create my first R shiny app. I was thinking of writing a code in which 2 separate csv files would be read and then combined into a single dataframe. I need to add a couple columns in each dataframe before combining them, as shown in the code. So I thought I could manipulate the data outside of the ui and server and then create the app which would allow the user to select what they want to be plotted on each axis. The first part of the code outside the shiny part works fine and I get the desired combined dataframe. However, when I run the code the dataframe does not seem to be created and as such I end up with an empty interface.
Any help would be greatly appreciated! Attached I have a picture of the columns in one of the csv files, the second csv file is similar.
library(tidyverse)
library(shiny)
twofiles<-c("shop1.csv","shop2.csv")
shop_list<-lapply(twofiles, read.csv, header=TRUE, sep=",")
shop_list<- lapply(seq_along(shop_list), function(i){
df <- shop_list[[i]]
df<-transform(df,ratio1=price_apples/price_pears)
df<-transform(df,ratio2=price_apples/price_cherries)
df<-transform(df,datano=i)
})
finaldata <- do.call(rbind, shop_list)
finaldata$datano <- factor(finaldata$datano)
ui<-fluidPage(
titlePanel("Shops plots"),
sidebarMenu(
selectInput(inputId = "x", label = "Select x-axis:",
choices = c("Year"="year","Hour"="hour"), selected="year"),
selectInput(inputId = "y", label = "Select y-axis:",
choices = c("Ratio 1"="ratio1","Ratio 2"="ratio2"),selected="ratio1"),
mainPanel(
plotOutput("plot")
)
)
)
server<-function(input, output) {
output$plot <-renderPlot({
ggplot(finaldata, aes(x=input$x, y=input$y, group=datano, color = datano)) +
geom_line()
})
}
shinyApp(ui=ui, server=server)
Too long for comments:
Here is the example code with the mtcars
dataset:
You have to use aes_string
not aes
in ggplot
.
Dataframe manipulation including loading etc.. should be done server side.
One more thing is that group=datano
and color=datano
may prone to the problem also. Try here yourdataframe$datano
library(shiny)
library(dplyr)
library(ggplot2)
ui<-fluidPage(
titlePanel("XXX"),
sidebarMenu(
selectInput(inputId = "x", label = "Select x-axis:",
choices = c("mpg"="mpg","disp"="disp"), selected="mpg"),
selectInput(inputId = "y", label = "Select y-axis:",
choices = c("hp"="hp","drat"="drat"),selected="hp"),
mainPanel(
plotOutput("plot")
)
)
)
server<-function(input, output,session) {
output$plot <-renderPlot({
ggplot(finaldata, aes_string(x=input$x, y=input$y, group=mtcars$cyl, color = mtcars$cyl)) +
geom_line()
})
}
shinyApp(ui=ui, server=server)