我正在尝试从多个复选框组中获取输入,但只有最后一个复选框组(标记为industry
)才会显示其内容。我在这做错了什么?请注意复选框选项如何在不同的子标题下重复。
我的代码:
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,]
ui = bootstrapPage(
titlePanel("Occupation by Race and Age"),
sidebarLayout(
sidebarPanel(
checkboxGroupInput('age',"Choose Age/Racial Group(s)", choices=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({
cat(paste0("in_get_data_\n",input$age))
cat(paste0("in_get_data2_\n",input$industry))
shiny::validate(need(input$age!="", "Please select an age"))
shiny::validate(need(input$industry!="", "Please select an industry"))
#ages are x axis, y are industry values
data<-csv[grepl(input$age,row.names(csv)),] #filter only selected ages (rows)
data<-data[,grepl(input$industry,colnames(csv))] #filter only selected industry (column)
data
})
output$plot1 <- renderPlot({
data<-getData()
shiny::validate(need(length(data)>1, "The data for the source you selected was not reported"))
plot(data,names.arg=colnames(data),legend.text = T,beside=T,col =palette()[1:nrow(data)])
})
}
shinyApp(ui, server)
答案 0 :(得分:2)
我会改变很多事情。
age
选择框您将错误的值传递给第一个复选框,请尝试:
choices = unique(as.data.frame(csv)[,1])
choices
参数在回复讨论时,在this answer之后的评论中,如果您打算将unique(as.data.frame(csv)[,1])
用作复选框的choices
参数的标签和值,则可以创建以下列方式列出必要的清单:
choicesList <- as.list(unique(as.data.frame(csv)[,1]))
names(choicesList) <- as.list(unique(as.data.frame(csv)[,1]))
您稍后可以转到复选框功能:choices = choicesList
。
值得补充的是,您可以同时过滤两种情况:
data <-
csv[grepl(input$age, row.names(csv)) ,
grepl(input$industry, colnames(csv))]
还有其他值得修复的事情。运行代码:
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,]
将生成:
>> head(csv)
Error in x[needs_ticks] <- paste0("`", gsub("`", "\\\\`", x[needs_ticks]), :
NAs are not allowed in subscripted assignments
如果你看一下:
>> head(as.data.frame(csv))
NA Mining,\r\nquarry-\r\ning,\r\nand oil\r\nand gas\r\nextract-\r\nion
1 TOTAL <NA>
2 Total, 16 years and over 792
3 16 to 19 years 4
4 20 years and over 788
5 20 to 24 years 45
6 25 years and over 743
使用此数据框将是一场噩梦。你可以从更改列名到语法正确的名称开始,大多数残酷的方法都涉及使用make.names
函数:
>> make.names(names(as.data.frame(csv)))
[1] "NA."
[2] "Mining...quarry...ing...and.oil..and.gas..extract...ion"
[3] "Con...struc...tion"
恕我直言,我认为首先修复数据框然后派生UI元素并实现子集逻辑是值得的,因为试图利用当前可用的值会因为奇怪的内容而成为问题: {{1} } 强>