I am new to R and am trying to create Shiny app.
The app contains sliderInput to determine the investment amount.
The selectInput to determine vehicle type to invest in (car or motorcycle)
and another selectInput to pick the brand name.
My requests are:
- After selecting the vehicle type (
carormotorcycle), automatically select the rows that contain the selected vehicle type ( for example "cars") - After that, sum the values in
profitcolumn and divide each one by the total to calculate each brand name contribution in total profits. - Add new column that contains percentage of each brand
name - Then add new column that contains multiplication of the
sliderInputvalue to this percentage to calculate the expected profit if we invested the amount insliderInput. - Then create bar plot for each brand
namewith their profits
Here is the code :
library(shiny)
library(dplyr)
library(plotly)
df1<-
data.frame (
Vehicle_type=c("CAR","CAR","CAR","MOTORCYCLE","MOTORCYCLE","MOTORCYCLE"),Brand_Name=c("ford","Honda","Audi","SYM","Honda","Harley"),revenues=(as.integer(c("526","552","445","222","223","300"))),cost=(as.integer(c("426","427","325","172","178","235"))),profit=(as.integer(c("100","125","120","50","45","65"))),branch1=(as.integer(c("10","15","12","6","5","5"))),branch2=(as.integer(c("3","4","7","6","4","9"))))
shinyUI(fluidPage(titlePanel("Vehicles"),
sidebarLayout(sidebarPanel(sliderInput("bins", "investment:", min = 1000,max = 10000,value = 5000),
selectInput("ProductId","Vehicle type:",choices=unique(df1$Vehicle_type)),
selectInput("nameId","Vehicle Brand Name:",choices=NULL),
selectInput("IndicatorId","Select Indicator:",choices=c("profit","cost","revenues",selected="revenues"))),
mainPanel(plotlyOutput("Test2", height = "250px")))))
server
library(shiny)
library(dplyr)
library(plotly)
shinyServer(function(session,input, output) {
observe({
print(input$ProductId)
df2<-df1%>%filter(Vehicle_type==input$ProductId) %>% select(Brand_Name)
updateSelectInput(session,"nameId","Vehicle Brand Name:",choices=unique(df2))
IndicatorSum<- reactive({df2 %>% pull(input$IndicatorId) %>% sum()})
df3<-mutate(df2,perctcontcl=input$IndicatorId/IndicatorSum)
df4<-mutate(df3,perctcontout=perctcontcl*input$bins)
output$Test2 <- renderPlotly({
Test2 <- plot_ly(
df4, x = ~Brand_Name, y = ~get(input$IndicatorId), type = "bar",color=~Brand_Name)})
})
})
shinyServer(function(input, output) {})