R:从选定的输入中获取总和

R: get sum from selected Input

我是 R 的新手,正在努力自学。

我想在闪亮的仪表板中创建一个 select 字段,我可以在其中选择我的数据 (.xls) 的产品并返回总和。

输入是通过 selectInputselectize。这是有效的部分:)

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

我的问题是想选择比 1 更多的产品并计算卡路里的总和。我如何 identify/search 我的 table 中输入字段的乘积以及我如何得到它的总和?

非常感谢您的帮助!

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)

我们需要 'ui' 中的 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 <- 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)

-数据

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)`

-输出