2

I have inputfile with my database and i want to make calculation on it.

I'm begginer with shiny app and I don't know how can I filter or add the columns.

My database looks like this:

x1 x2 type1 x3 x4 type2
0.2 1.1 Y 6 4.2 0
0.5 3.3 N 1.8 7.0 0
0.8 0.5 Y 2.5 11 1

My question in how can I make simple calculation like x1+x2, if database is from my own inputfile like this:

ui <- fluidPage(fileInput('file', label = "Read file.csv", accept ="text/csv")

in server I use:

data <- reactive(read_csv2(input$plik$datapath))

but my problem is how can i use expresion like data$x1 or my calculation like data$x2*data$x3.

Aga G.
  • 31
  • 2
  • 1
    Should that be `input$file$datapath` (instead of `plik`)? – r2evans Dec 16 '21 at 14:13
  • 1
    Shiny reactive data is akin to a function, so you use it as `data()$x1`, covered in [Lesson 6](https://shiny.rstudio.com/tutorial/written-tutorial/lesson6/) of RStudio's shiny tutorial. Note: since the user uploads the data, you may want to be more defensive and programmatic with accessing columns and not hard-code `$x1` as a column name. – r2evans Dec 16 '21 at 14:15
  • Yes it should be data <- reactive(read_csv2(input$file$datapath)) – Aga G. Dec 17 '21 at 06:36

1 Answers1

0

Reactive values can be used like regular objects but you need to call them like a function. Below is an example using df() that is a reactive data.frame.

library(tidyverse)
library(shiny)

# create data
write.csv(
  x =
    tibble::tribble(
      ~x1, ~x2, ~type1, ~x3, ~x4, ~type2,
      0.2, 1.1,    "Y",   6, 4.2,     0L,
      0.5, 3.3,    "N", 1.8,   7,     0L,
      0.8, 0.5,    "Y", 2.5,  11,     1L
    ), row.names = FALSE,
  "database.csv"
)

library(shiny)

ui <- fluidPage(
  sidebarLayout(
    sidebarPanel(
      fileInput("upload", NULL),
      selectInput("sum", "Select Columns to sum", choices = "", multiple = TRUE),
      actionButton("perform_sum", "Sum")
    ),
    mainPanel(tableOutput("table"))
  )
)

server <- function(input, output, session) {
  df <- reactiveVal(NULL)
  #read the data
  observeEvent(input$upload, {
    data <- read_csv(input$upload$datapath)
    df(data)
    updateSelectInput(session, "sum", choices = names(df()))
  })
  #perform sum
  observeEvent(input$perform_sum, {
    req(df())
    df(df() %>%
      mutate('sum_{reduce(input$sum, paste, sep = \"_\")}' := rowSums(across(all_of(input$sum)))))
  })
  #render table
  output$table <- renderTable({
    req(df())
    df()
  })
}

shinyApp(ui, server)

enter image description here

jpdugo17
  • 6,816
  • 2
  • 11
  • 23