Search code examples
rshinyr-markdownflexdashboard

Adjustment renderValueBox function in R


I created a function to calculate predicted values ​​according to 3 variables.

However I am unable to adjust the renderValueBox function to make the calculation.

The code is here (write in rmarkdown):

---
title: "Untitled"
runtime: shiny
output: 
  flexdashboard::flex_dashboard:
    orientation: rows
    vertical_layout: fill
    theme: cosmo
---

```{r}
library(tidyverse)

df_2 <- data.frame(
  m = seq(from = .05, to = .95, by = .05), 
  d = seq(from = .04, to = .94, by = .05), 
  q = c(1:18, 2000)
)

desconto <- function(mc, desc, qtde) {
  ((((mc) / (mc - desc)) - 1) * qtde + qtde)
}

price <- desconto(
  mc = df_2$m, 
  desc = df_2$d, 
  qtde = df_2$q
)
```

```{r}
library(shiny)
library(flexdashboard)
```
```

Predict values
=================================
Sidebar{.sidebar data-width=300}
---------------------------------

```{r}
# Widgets
sliderInput(
  inputId = 'm', label = 'mc', 
  value = mean(round(x = df_2$m, digits = 0)) * 100, 
  min = min(round(x = df_2$m, digits = 0)) * 100, 
  max = max(round(x = df_2$m, digits = 0)) * 100
)

sliderInput(
  inputId = 'd', label = 'dc', 
  value = mean(round(x = df_2$d, digits = 0)) * 100, 
  min = min(round(x = df_2$d, digits = 0)) * 100, 
  max = max(round(x = df_2$d, digits = 0)) * 100
)

numericInput(
  inputId = 'q', label = 'qtde', 
  value = mean(round(x = df_2$q, digits = 0)), 
  min = min(round(x = df_2$q, digits = 0)), 
  max = max(round(x = df_2$q, digits = 0))
)
```

```{r}
# Reactive object
reac_1 <- reactive({
  tibble(
    m = input$m, 
    d = input$d, 
    q = input$q
  )
})

# Reactive output
pred_4 <- reactive({
  x = reac_1()$price
})
```

Calculator{}
----------------------
```{r}
renderValueBox(
  valueBox(
    value = pred_4()
  )
)
```

For example, for mc = 50, dc = 20 and qtde = 1500 the expected result would be 2500.

  • The problem is in the function renderValueBox

Thank's a lot.


Solution

  • The issue is the line reac_1()$price. Look at how you define reac_1, there is no price column. (You also don't ever use the price object that you define in the first code chunk, I'd delete it for clarity)

    One solution modifies pred_4 like this:

    pred_4 <- reactive({
      temp <- reac_1()
      desconto(
      mc = temp$m,
      desc = temp$d,
      qtde = temp$q
    )
    })