我是R的新手,正在尝试创建Shiny应用程序。
该应用程序包含sliderInput
以确定投资金额。
selectInput
确定要投资的车辆类型(car
或motorcycle
)
另一个selectInput
选择品牌name
。
我的要求是:
car
或motorcycle
)后,自动选择包含所选车辆类型(例如“ cars”)的行profit
列中的值相加,然后将每个值除以总数,以计算每个品牌对总利润的贡献。name
的百分比sliderInput
值乘以该百分比,以计算如果我们将金额投资到sliderInput
中的预期利润。然后为每个品牌name
及其利润创建条形图
这是代码:
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")))))
服务器
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) {})