Search code examples
rshinytextinput

Have users specify new variable name and definition using textInput


I would like my users to create a new variable and add it to an existing data frame. The users need to enter the name and definition through textInput. Note: I have tried all suggestions posted in Getting strings recognized as variable names in R

Still, I am not able to make it work. Any suggestions will be greatly appreciated. Thank you!

Here is my code:

rawdata:

colA <- c('1','2','3','3','2')
colB <- c('1','1','3','3','2')
colC <- c('14','12','33','33','26')
colD <- c('Value','Mainstream','Value','Premium','Premium')
colE <- c(1,2,3,4,5)
rawdata <- as.data.frame(cbind(colA, colB, colC, colD, colE))

ui.R:

fluidPage(
            sidebarLayout(
                sidebarPanel(
                  textInput("NewVar_Name", "New attribute's name"), 
                  textInput("NewVar_Def", "New attribute's definition", 
                            "ifelse(rawdata$price_tiers_new == 'Value', 1, 0)"),

                    br(),
                    actionButton("addButton", strong("Done!")),
                    width = 3
                ),

                mainPanel(
                    verticalLayout(
                        br()
                        #Will display a summary of new variable
                    )
                )
           )
        )

server.R:

function(input, output, session) {

    temp   <- reactiveValues()

    observe(
        if(input$addButton == 0) {
            temp$df <- rawdata
        } else {
            temp$df <- mydata()
        }
    )


    mydata <- eventReactive(input$addButton, {
        if(input$addButton == 0) {
            rawdata
        } else {
             tempname <- eval(as.name(input$NewVar_Name))
             do.call("<-",list(tempname, eval(parse(text=input$NewVar_Def))))

             cbind(temp$df, tempname)
        }
    })

}

Solution

  • I guess you could do

    mydata <- eventReactive(input$addButton, {
        if(input$addButton == 0) {
          rawdata
        } else {
          tempdata <- eval(parse(text=input$NewVar_Def))
          temp$df <- setNames(cbind(
            temp$df, 
            tempdata), 
            c(names(temp$df), input$NewVar_Name))
        }
    })
    

    Note that ifelse(rawdata$price_tiers_new == 'Value', 1, 0) will not work, because the data set has no column named price_tiers_new.