2015-09-19 42 views
1

我正在嘗試使用USArrests數據庫構建一個簡單的Shiny應用程序,該應用程序顯示密度人口與犯罪(謀殺,突擊,強姦)3個變量之間的相關性,使用selectInpuct更改犯罪變量。Shiny Correlation Plot

這裏ui.R的代碼:

shinyUI(fluidPage(
    titlePanel("Violent Crime Rates by US State"), 

    sidebarLayout(
     sidebarPanel(
      helpText("A series of plots that display correlation between density population and various kind of crimes"), 

      selectInput("var", 
         label = "Choose a crime", 
         choices = c("Murder"=1, "Assault"=2, 
             "Rape"=4), 
         selected = "Murder") 


      ), 

     mainPanel(plotOutput('crimeplot')) 
    ) 
)) 

和server.R

shinyServer(function(input,output){ 


output$crimeplot<- renderPlot({ 
    x<-as.numeric(input$var) 
    y<-as.numeric(USArrests$UrbanPop) 

    plot(x, y, log = "xy") 




}) 

}

但運行它返回的應用:

ERROR:' x'和'y'長度不同

你能幫我解釋一下我在做什麼?

非常感謝您提前!

回答

1

我發現了一些我在下面的代碼中已經修復的小錯誤。

  • 您的選擇返回列號(字符串),你需要將其轉換爲一個數字,在server.R提取數據幀中的相關列。
  • selected的默認值ui.R應該是起始值而不是標籤。

更新server.R如下所示

shinyServer(function(input,output){ 
       output$crimeplot<- renderPlot({ 
        x<-as.numeric(USArrests[,as.numeric(input$var)]) 
        y<-as.numeric(USArrests$UrbanPop) 
        plot(x, y, log = "xy", xlab=colnames(USArrests)[as.numeric(input$var)], ylab="Urban Pop") 
       }) 
      }) 

ui.R看起來是這樣的:

shinyUI(fluidPage(
    titlePanel("Violent Crime Rates by US State"),  
    sidebarLayout(
     sidebarPanel(
      helpText("A series of plots that display correlation between density population and various kind of crimes"), 

      selectInput("var", 
         label = "Choose a crime", 
         choices = c("Murder"=1, "Assault"=2, 
          "Rape"=4), 
         selected = 1) 
      ), 

     mainPanel(plotOutput('crimeplot')) 
     ) 
    )) 
+1

親愛ekstroem,它的作品!非常感謝您的幫助和解釋! – 3lli0t