R:从所选输入中获得总和

时间:2017-09-04 20:22:50

标签: r shiny shinydashboard

我是R的新手,并试图独自学习。

我想在一个闪亮的仪表板中创建一个选择字段,在那里我可以选择我的数据产品(.xls)并获得一笔总和。

输入是通过 selectInput 选择。这是部分,有效:)

如果我选择1种产品,我将获得该产品的卡路里......到目前为止。

我的问题是想要选择更多的产品然后1并获得卡路里的总和。我如何识别/搜索表格中输入字段的产品,如何得到它的总和?

非常感谢你的帮助!

PS:您还需要有关文件的更多信息吗?只有两列对此很重要:产品和卡路里。

library(dplyr)
library(plotly)
library(readxl)
library(shiny)
library(shinydashboard)

# Daten einlesen
McDaten <- read_excel("~/Desktop/McDaten.xlsx")
McDaten$kcal <- McDaten$`kcal (100g)`

ui <- dashboardPage(
skin="red",
dashboardHeader(title = "Analytics Dashboard", titleWidth = 290),
dashboardSidebar(
width = 290,
sidebarMenu(
  menuItem("Virtuelles Menü", tabName = "charts", icon = icon("cutlery"))

)
  ),

  dashboardBody(


tabItems(

  tabItem(tabName = "charts",
          fluidPage(
            br(),
            fluidRow(
              column(4,
                     selectInput('in6', 'Menü', McDaten$Produkt, multiple=TRUE, selectize=TRUE)),
              column(4,infoBoxOutput("progressBox"))
            )
          )

  ))))


server <- function(input, output) {

  output$progressBox <- renderInfoBox({
    b <- McDaten %>%
  select(`kcal (Portion)`, Produkt) %>%
  filter(McDaten$Produkt %in% input$in6) %>%
  summarise(`kcal (Portion)`)

infoBox(
  "Progress", paste0(b, " kcal"), icon = icon("list"),
  color = "purple", fill = TRUE
)
  })

}


shinyApp(ui, server)

1 个答案:

答案 0 :(得分:0)

我们需要&{39}中的choices = unique(McDaten$Produkt)。并且在summarise中需要为感兴趣的列指定sum

-ui

ui <- dashboardPage(
  skin="red",
  dashboardHeader(title = "Analytics Dashboard", titleWidth = 290),
  dashboardSidebar(
    width = 290,
    sidebarMenu(
      menuItem("Virtuelles Menü", tabName = "charts", icon = icon("cutlery"))

    )
  ),

  dashboardBody(


    tabItems(

      tabItem(tabName = "charts",
              fluidPage(
                br(),
                fluidRow(
                  column(4,
                     selectInput('in6', 'Menü', 
                       choices = unique(McDaten$Produkt), multiple=TRUE, selectize=TRUE )),
                  column(4,infoBoxOutput("progressBox"))
                )
              )

      ))))

-server

server <- function(input, output) {

  output$progressBox <- renderInfoBox({
    b <- McDaten %>%
      select(`kcal (Portion)`, Produkt) %>%
      filter(Produkt %in% input$in6) %>%
      summarise(`kcal (Portion)` = sum(`kcal (Portion)`)) %>%
      pull(`kcal (Portion)`)


    infoBox(
      "Progress", paste0(b, " kcal"), icon = icon("list"),
      color = "purple", fill = TRUE
    )
  })

}

- 运行应用

shinyApp(ui, server)

-data

set.seed(24)
McDaten <- data.frame(Produkt = sample(LETTERS[1:5], 30, replace = TRUE),
   `kcal (Portion)` = sample(1400:2000, 30, replace = TRUE), 
        stringsAsFactors= FALSE, check.names = FALSE)

McDaten$kcal <- McDaten$`kcal (Portion)`

-output

enter image description here

enter image description here