在闪亮的情况下,如何从包含基于selectinputs添加列的sliderinput进行绘制

时间:2019-09-27 14:42:40

标签: r shiny

我是R的新手,正在尝试创建Shiny应用程序。 该应用程序包含sliderInput以确定投资金额。 selectInput确定要投资的车辆类型(carmotorcycle) 另一个selectInput选择品牌name

我的要求是:

  1. 选择车辆类型(carmotorcycle)后,自动选择包含所选车辆类型(例如“ cars”)的行
  2. 然后,将profit列中的值相加,然后将每个值除以总数,以计算每个品牌对总利润的贡献。
  3. 添加新列,其中包含每个品牌name的百分比
  4. 然后添加新列,该列包含sliderInput值乘以该百分比,以计算如果我们将金额投资到sliderInput中的预期利润。
  5. 然后为每个品牌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) {})

1 个答案:

答案 0 :(得分:1)

这里有一个基于您的想法的可行示例,并提供了一些修复程序和dplyr NSE的一些帮助

>>>id
<built-in function id>