【问题标题】:Have users specify new variable name and definition using textInput让用户使用 textInput 指定新的变量名称和定义
【发布时间】:2017-11-20 14:53:57
【问题描述】:

我希望我的用户创建一个新变量并将其添加到现有数据框中。用户需要通过 textInput 输入名称和定义。注意:我已经尝试了Getting strings recognized as variable names in R中发布的所有建议

不过,我无法让它工作。任何建议将不胜感激。谢谢!

这是我的代码:

原始数据:

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

服务器.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)
        }
    })

}

【问题讨论】:

标签: r shiny textinput


【解决方案1】:

我猜你可以做到

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

请注意ifelse(rawdata$price_tiers_new == 'Value', 1, 0) 将不起作用,因为数据集没有名为price_tiers_new 的列。

【讨论】:

  • 你是对的。 Price_tiers_new 在我的其他数据集中可用,因此在这种情况下不起作用。但是您的建议非常有效。谢谢!
猜你喜欢
  • 1970-01-01
  • 2022-01-15
  • 2011-11-30
  • 2015-05-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多