由于输入数据帧错误,barplot无法显示

时间:2017-03-07 00:35:46

标签: r dataframe shiny bar-chart

有人可以解释我试图显示数据的数据框有什么问题吗?抛出错误的行标有注释。

library(dplyr)
library(shiny)
dlxl<-function(url,sht){
  tmp = tempfile(fileext = ".xlsx")
  download.file(url = url, destfile = tmp, mode="wb")
  library(readxl)
  read_excel(tmp,sheet=sht)
}
csv<-dlxl("https://www.bls.gov/cps/cpsa2016.xlsx",sht="cpsaat14")
colnames(csv)<-csv[4,]
csv<-csv[6:81,]
colnames(csv)<-make.names(names(as.data.frame(csv)))

ui = bootstrapPage(
  titlePanel("Occupation by Race and Age"),

  sidebarLayout(
    sidebarPanel(
      checkboxGroupInput('age',"Choose Age/Racial Group(s)", choices = unique(as.data.frame(csv)[,1]),selected=NULL),
      checkboxGroupInput('industry',"Choose Industries", choices=colnames(csv),selected=NULL)
    ),
    mainPanel(
      plotOutput("plot1"),
      htmlOutput("text1")
    )
  )
)
server = function(input, output, session){

  output$text1 <- renderUI({HTML(paste("GO"))})

  getData<-reactive({
    shiny::validate(need(length(input$age)>1, "Please select an age"))
    shiny::validate(need(length(input$industry)>1, "Please select an industry"))
    #ages are x axis, y are industry values
    data <-csv[,grepl(input$industry, colnames(csv))]
    data<-cbind(csv[,1],data)
    data2<-data[grepl(input$age, data[,1]),]
    as.data.frame(data2)
})

  output$plot1 <- renderPlot({
    data<-getData()
    shiny::validate(need(nrow(data)>1, "The data for the source you selected was not reported"))
    barplot(data[,2:ncol(data)]) #########ERROR HERE
    #browser()
    #plot(data,names.arg=colnames(data),legend.text = T,beside=T,col =palette()[1:nrow(data)])
  })
}

shinyApp(ui, server)

1 个答案:

答案 0 :(得分:0)

一对错误:

>1更改为>0以检查所选的一个参数(不需要两个)

shiny::validate(need(length(input$age)>0, "Please select an age"))
shiny::validate(need(length(input$industry)>0, "Please select an industry"))

read_excel似乎将所有数字都读为字符串,您必须先使用as.numeric将其转换为数字,然后才能进行绘图:

barplot(as.numeric(data[,2:ncol(data)]))