1

In my reactive dataframe, one column has a reactive name (chosen by the user) and I would like to generate a column whose values are the logarithm of the original column. To do so, I use mutate in the dplyr package. However, when I try to make the name of this new column reactive, there's an error.

For example, in the code below, I name the new column "logarithm" and it works fine:

library(shiny)
library(DT)
library(data.table)
library(dplyr)

ui <- fluidPage(
  titlePanel(""),
  fluidRow(
    checkboxInput(inputId = "logarithm",
                  label = "Log(variable)"),
    dataTableOutput("my_df"),
    textInput("new_name", 
              label = "New_name"),
    actionButton("new_name2", "Validate")
  )
)


server <- function(input, output) {

  data <- head(mtcars[, 1:3])


  reactive_data <- eventReactive(input$new_name2, {
    colnames(data) <- c("mpg", "cyl", input$new_name)
    data
  }) 

  output$my_df <- renderDataTable({
    data <- reactive_data()
      if(input$logarithm){
        data %>%
          mutate(logarithm = log(data[, input$new_name]))

      }
    else {
      data
    }
  })
}

shinyApp(ui = ui, server = server)

But change "logarithm" by "logarithm(input$new_name)" and it won't work anymore.

Does anybody have a solution?

bretauv
  • 7,756
  • 2
  • 20
  • 57

1 Answers1

1

Based on this question and answer

if(input$logarithm){
        log_name <- paste0('logarithm(', input$new_name, ')')
        data %>%
          mutate(!!log_name := log(data[, input$new_name]))

}

Full code:

library(shiny)
library(DT)
library(data.table)
library(dplyr)

ui <- fluidPage(
  titlePanel(""),
  fluidRow(
    checkboxInput(inputId = "logarithm",
                  label = "Log(variable)"),
    dataTableOutput("my_df"),
    textInput("new_name", 
              label = "New_name"),
    actionButton("new_name2", "Validate")
  )
)


server <- function(input, output) {

  data <- head(mtcars[, 1:3])


  reactive_data <- eventReactive(input$new_name2, {
    colnames(data) <- c("mpg", "cyl", input$new_name)
    data
  }) 

  output$my_df <- renderDataTable({
    data <- reactive_data()
    if(input$logarithm){
            log_name <- paste0('logarithm(', input$new_name, ')')
            data %>%
              mutate(!!log_name := log(data[, input$new_name]))

    }
    else {
      data
    }
  })
}

shinyApp(ui = ui, server = server)
Eli Berkow
  • 2,628
  • 1
  • 12
  • 22