2016-10-02 117 views
0

我想從Shiny聚合一個反應表。我的結構類似於this example如何聚合閃亮的反應表?

library(shiny) 

runApp(list(
    ui=pageWithSidebar(headerPanel("Adding entries to table"), 
        sidebarPanel(textInput("text1", "Column 1"), 
            textInput("text2", "Column 2"), 
            actionButton("update", "Update Table")), 
        mainPanel(tableOutput("table1"))), 
    server=function(input, output, session) { 
    values <- reactiveValues() 
    values$df <- data.frame(Column1 = NA, Column2 = NA) 
    newEntry <- observe({ 
     if(input$update > 0) { 
     newLine <- isolate(c(input$text1, input$text2)) 
     isolate(values$df <- rbind(values$df, newLine)) 
     } 
    }) 
    output$table1 <- renderTable({values$df}) 
    })) 

我試圖用多種方法,例如:

output$table2 <- renderTable({ 
    as.data.frame(values$Column1, list(values$Column2), sum 
}) 

但是到現在爲止我也沒有預期的結果。你有想法嗎?

+0

抱歉的版本。這是我第一次來... –

+0

預期的結果是什麼?這只是添加值?或添加第二個表? – Geovany

+0

添加第二個包含彙總值的表格。 例如,如果第1列是數字,而第2列是在條目的一欄中從A到E的字母。然後例如按字母(函數和)聚合一列。 –

回答

1

您是否正在尋找像行數一樣的東西?我sum使用apply功能,但

output$table1 <- renderTable({cbind(values$df, Rowsum = apply(values$df, 1, function(x) sum(as.numeric(x))))}) 

另外,如果你想刪除的第一個空行,你可以使用的建議SO問你linked

它看起來像這樣:

enter image description here

完整代碼:

library(shiny) 

runApp(list(
    ui=pageWithSidebar(headerPanel("Adding entries to table"), 
        sidebarPanel(textInput("text1", "Column 1"), 
            textInput("text2", "Column 2"), 
            actionButton("update", "Update Table")), 
        mainPanel(tableOutput("table1"))), 
    server=function(input, output, session) { 
    values <- reactiveValues() 
    values$df <- data.frame(Column1 = numeric(0), Column2 = numeric(0)) 
    newEntry <- observe({ 
     if(input$update > 0) { 
     newLine <- isolate(c(input$text1, input$text2)) 
     isolate(values$df[nrow(values$df) + 1,] <- c(input$text1, input$text2)) 
     } 
    }) 
    output$table1 <- renderTable({cbind(values$df, Rowsum = apply(values$df, 1, function(x) sum(as.numeric(x))))}) 
    })) 

請注意,沒有執行異常處理。

+0

Thanks ....我的代碼中有一個錯誤: 輸出$ table2 < - renderTable({aggregate(values $ column1,list(values $ column2),sum) 我忘了寫聚合... –

+0

沒問題,查看鏈接的stackoverflow問題中刪除空行的建議(也在我的代碼中實現) 也歡迎Stack Overflow。如果這個答案或其他解決了你的問題,請將它標記爲 – GyD

+0

是的,那是!放好NAS,謝謝你非常。這裏我的代碼: 輸出$ table2 < - renderTable({(聚合(as.numeric(values $ df $ Column1),(list(Variety = values $ df $ Column2)),sum))}) –