2016-01-06 44 views
1

我構建了一個查詢SQL數據庫的閃亮應用程序,因此用戶可以ggplot數據。我希望用戶能夠手動重命名因素,但我正在努力前進。下面是我想要做的一個例子:閃亮 - 反應數據框中的重命名因素

ui.R

library(markdown) 

shinyUI(fluidPage(
    titlePanel("Reactive factor label"), 
    sidebarLayout(
    sidebarPanel(

     numericInput("wafer", label = h3("Input wafer ID:"), value = NULL), 

     actionButton("do", "Search wafer"), 
     textInput("text", label = h3("Factor name to change"), value = ""), 
     textInput("text", label = h3("New factor name"), value = ""), 
     actionButton("do2", "Change name") 

     ), 

    mainPanel(
     verbatimTextOutput("waf"), 
     verbatimTextOutput("que"), 
     verbatimTextOutput("pos"), 
     dataTableOutput(outputId="tstat") 
    ) 
) 
) 
) 

server.R

# Create example data 

Name <- factor(c("Happy", "New", "Year")) 
Id <- 1:3 

dd <- data.frame(Id, Name) 

con <- dbConnect(RSQLite::SQLite(), ":memory:") 
dbWriteTable(con, "dd", dd) 
query <- function(...) dbGetQuery(con, ...) 

wq = data.frame() 
sq = data.frame() 


shinyServer(function(input, output){ 

    # create data frame to store reactive data set from query 
    values <- reactiveValues() 
    values$df <- data.frame() 

    # Wait for user to search 
    d <- eventReactive(input$do, { input$wafer }) 

    # Reactive SQL query 
    a <- reactive({ paste0("Select * from dd where Id=",d()) }) 
    wq <- reactive({ query(a()) }) 

    # Check outputs 
    output$waf <- renderPrint(input$wafer) 
    output$que <- renderPrint({ a() }) 
    output$pos <- renderPrint(wq()[1,1]) 

    # observe d() so that data is not added until user presses action button 
    observe({ 
    if (!is.null(d())) { 
     sq <- reactive({ query(a()) }) 

     # add query to reactive data frame 
     values$df <- rbind(isolate(values$df), sq()) 
    } 
    }) 

    output$tstat <- renderDataTable({ 
    data <- values$df 
    }) 

}) 

在靜態RI通常會使用數據表重命名因素,如:

DT <- data.table(df) 
DT[Name=="Happy", Name:="Sad"] 

但我不知道如何去做這個與reactiveValues即values$df

我已閱讀此(R shiny: How to get an reactive data frame updated each time pressing an actionButton without creating a new reactive data frame?)。這導致我嘗試這一點,但它不會做任何事情(即使沒有錯誤):

observeEvent(input$do2, { 
    DT <- data.table(values$df) 
    DT[Name == input$text1, Name := input$text2] 
    values$df <- data.frame(values$df) 

    }) 

或許有圍繞this..maybe的方式存在使用動作按鈕「鎖定」的方式數據作爲一個新的數據框架,然後可以用它來重命名?

對不起這麼長時間的問題。我的真實應用程序更長,更復雜。我試圖剝奪它。

+0

可能相關:http://stackoverflow.com/q/20201070/2679518如果你的'data.frame'本身就是一個被動對象,你將無法改變'data.frame'本身的名字。 –

回答

1

您的方法可行,但您的應用中存在一些問題。

ui.R,無論textInput具有相同的id,他們需要的是不同的,所以你可以參考他們在server.R。在您發佈的observeEvent中,您指的是input$text1input$text2,因此您應該將textInputsid更改爲text1text2

observeEvent您發佈,最後一行應該是values$df <- as.data.frame(DT),否則它不會改變任何東西。

+0

啊哈!愚蠢的錯誤!非常感謝你。 – Pete900