Search code examples
rshinyr-caret

R function in shiny doesn't work with an input in Shiny


so i have the next chunk of code on my shiny app:

observeEvent(input$change_type_btn,{
    req(input$var_cambio)
    
    selected_column <- input$var_cambio

    data(data() %>% mutate(Age = as.numeric(Age)))

  })

As you can see, y have a dataframe called data() and I want to change the type of a column into numeric. as an example I use the column Age which is stored as a char type. This works perfectly.

But the moment I have a SelectInput where I want to select the column to swap like this:

selectInput(
          "var_cambio",
          label = "Selecciona la variable a cambiar de tipo:",
          choices = c(names(data())),
          multiple = FALSE,
          selected = NULL
        ),

and swap Age with input$var_cambio, the app closes instantly after executing It, returning a "Error in sourceUTF8(serverR, envir = new.env(parent = sharedEnv)) : Error sourcing C:/......./server.R

It's been hours, tried a lot of different things and i'm at my limit, I'm 99% sure It's because inputs should be used in another way or I'm missing something crucial about the topic I haven't learnt yet

i tried multiple ways to use the input by storing It as an auxiliar variable but It did not work


Solution

  • Does this help? It might have something to do with 'mutate' not receiving the correct column name from your input.

    observeEvent(input$change_type_btn, {
      # Ensure that a column has been selected
      req(input$var_cambio)
      
      # Convert the selected column name from string to a symbol
      selected_column <- rlang::sym(input$var_cambio)
      
      # Mutate the selected column to numeric, using non-standard evaluation
      data <- data() %> %> mutate(!!selected_column := as.numeric(.[[selected_column]]))
    })