0
votes

I want to create columns in an input csv file, but due to the characteristic of reactive, I can only make just one new column in the input file.

Here's my code.

 library(shiny)
library(rlang)
library(dplyr)
    
    ui <- fluidPage(
  fileInput("file","csv file", accept = c(".csv")),
  textInput("name","Variable name"),
  selectInput("sel","Variable selection", choices = colnames(file), multiple = T),
  actionButton("go","Go"),
  actionButton("mean","Mean"),
  dataTableOutput("DF")
)


server <- function(input, output, session) {
 
  appdata <- reactive({
    read.csv(input$file$datapath, header=TRUE, stringsAsFactors = FALSE, sep = ",",
             fileEncoding = "euc-kr") 
  })

  
  
  observeEvent(input$file,{
    
    output$DF <- renderDataTable({
      appdata()
    })
    updateSelectInput(session, "sel", label = "Variable", choices = colnames(appdata()))
  })
  
  
  observeEvent(input$mean,{
    rv <- reactiveValues(data=NULL)
    rv$data <- appdata()
    
    df <- eventReactive(input$mean,{
      req(input$mean, input$sel, input$name)
      var_name <- input$name
      mydf <- rv$data
      new_var <- mydf %>% transmute(!!var_name := rowMeans(select(., input$sel)))
      rv$data <- cbind(mydf, new_var)
    })
    output$DF <- renderDataTable({
      df()
      })
  })
      
 
}

shinyApp(ui, server)

As you can see, appdata is reactive that I put in the shiny server. That's why I can't help myself but putting rv$data <- appdata() in observeEvent().

Is there any way to create new columns in reactive data? Thanks in advance.

1

1 Answers

0
votes

Try :

library(shiny)
library(rlang)
library(dplyr)

ui <- fluidPage(
  fileInput("file","csv file", accept = c(".csv")),
  textInput("name","Variable name"),
  selectInput("sel","Variable selection", choices = colnames(file), multiple = T),
  actionButton("go","Go"),
  actionButton("mean","Mean"),
  dataTableOutput("DF")
)


server <- function(input, output, session) {
  rv <- reactiveValues(data=NULL)

  observeEvent(input$file,{
    rv$data <- read.csv(input$file$datapath, header=TRUE, stringsAsFactors = FALSE, sep = ",",
                        fileEncoding = "euc-kr") 
    output$DF <- renderDataTable({
      rv$data
    })
    updateSelectInput(session, "sel", label = "Variable", choices = colnames(rv$data))
  })

observeEvent(input$mean,{
    
      req(input$mean, input$sel, input$name)
      var_name <- input$name
      new_var <- rv$data %>% transmute(!!var_name := rowMeans(select(., input$sel)))
      cat('Add ',var_name,'\n')
      rv$data <- cbind(rv$data, new_var)
      
      output$DF <- renderDataTable({
        cat('update \n')    
        rv$data
      })
    })

}

shinyApp(ui, server)

enter image description here