1

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)
        }
    })

}
Ketty
  • 811
  • 10
  • 21
  • This should work for you: https://stackoverflow.com/questions/44598544/allow-users-to-add-new-variables-to-a-dataset-in-shiny-app/44599073#44599073 – Tonio Liebrand Jun 18 '17 at 09:22
  • That works perfectly to add new variables (thank you!). However, in that example, we do not get the variable names from users. – Ketty Jun 18 '17 at 10:21

1 Answers1

0

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.

lukeA
  • 53,097
  • 5
  • 97
  • 100
  • You are right. Price_tiers_new is available in my other dataset so it won't work in this case. But your suggestion works perfectly. Thank you! – Ketty Jun 18 '17 at 10:22