R语言_Shiny包-_学习笔记.docx
R语言_Shiny包学习笔记ZW2024-03-17ShinyApp的基本构成ShinyaPP有两部分(ui.R和SerVer.R可以放在一个R脚本文件中app.R): 一个用户交互脚本(ui):Ui负责控制布局和展示,在源脚本中固定的名称为ui.R 一个服务器脚本(server):SerVer.R脚本包含建立app计算机需要的基本说明文件夹内容如下(创建的WWW文件夹用来存放JS、CSS、图片、html等):PgrarnFiles>R>R-4.3.3>library>shiny>examples>08htmlXZ名称修改日期类型WWW2024/3/717:57文件夹0app.R2023/11/2216:43R文件DDESCRIPTION2023/11/2216:43文件oReadme.md9CreateShinyappI2023/11/2216:43MD文件ShinyAppId=htlTemplatef.,*widex.htlw,SerVerIibrary(Shiny)ui<-fluidPage(textoutput("greeting")server<-function(input,output,session)output$greeting<-renderText("Hellohuman!")shinyApp(ui=Ui,server=server)运行方式#app.R的路径Iibrary(Shiny)runApp("my_app")Shinyapps示例Youcanalsoembedplots,forexample:system.file("examples",package="shiny")runExample("0:LJIello")#ahistogramrunExample("02_text")#tabLesanddataframesrunExample("03_reactivity")#areactiveexpressionrunExample("04_mpg")#gLobaLVariabLesrunExample("05_sliders")#sLiderbarsrunExample("06_tabsets")#tabbedpaneLsrunExample("07_widgets")#heLptextandsubmitbuttonsrunExample("08_html")#ShinyappbutLtfromHTMLrunExample("09_upload")#fiLeupLoadwizardrunExample("10_download")#fiLedownloadwizardrunExample("ll_timer")#anautomatedtimer布局fluidPage函数来展示一个自动调整组件尺寸大小来适应浏览器,所有组件放在fluidPage函数中,得到整个app的布局。除了fluidPage()之外,Shiny还提供了一些其他的页面函数,这些函数可以在更专业的情况下派上用场:fixedPage()和fillPage()0Iibrary(Shiny)ui<-fluidPage(titlePanel("titlepanel"),SidebarLayout(position="right",sidebarPanel("sidebarpanel")jmainPanel("mainpanel")侧边栏(SidebarPaneI部分)默认出现在app的左边,通过调整Sidebar'Layout函数的一个参数position="right”将SidebarPanel调到右边。fluidPage()titlePanel()SidebarLayoutOsidebarPanel()mainPanel()tabsetPanel()为任意数量的tabPanels()创建一个容器,该容器又可以包含任何其他HTML组件。ui<-fluidPage(tabsetPanel(tabPanel("Importdata"jfile工叩Ut("file","Data",buttonLabel="Upload.textlnput("delim","Delimiter(leaveblanktoguess)","")4numericlnput("skip","Rowstoskip",0,min=0),numericinput("rows","Rowstopreview",10,min=1),tabPanel("Setparameters")jtabPanel("Visualiseresults")ImportdataSmPerwneterSVualeMEUlt3DateUpload.NofMeeeiectedDelimttef(leaveblanktoguess)Rowstoskjp0mRowstopreviow1。m如果你想知道用户选择了哪个选项卡,你可以向tabsetPanel提供id参数,它成为一个输入。Iibrary(Shiny)ui<-fluidPage(sidebarLayout(sidebarPanel(textoutput("panel"),mainPanel(tabsetPanel(id="tabsettabPanel(',panel1","one"),tabPanel("panel2","two"),tabPanel("panel3","three")server<-function(input,output,session)OUtPUt$Panel<-renderText(paste("Currentpanel:",input$tabset)shinyApp(ui=ui,server=server)navlistPanel()与tabsetPanel()类似,但它不是水平运行选项卡标题,而是在侧边栏中垂直显示它们。ui<-fluidPage(navlistPanel(id="tabset","Heading,tabPanel("panel1","Panelonecontents"),"Heading2",tabPanel("panel2","Paneltwocontents"),tabPanel("panel3","Panelthreecontents")另一种方法是使用navbarPage():它仍然水平运行选项卡标题,但您可以使用navbarMenu()添加下拉菜单以获得额外的层次结构级别。ui<-navbarPage("Pagetitle",tabPanel(,'panel1","one"),tabPanel("panel2","two"),tabPanel(,'panel3","three"),navbarMenu("subpanels",tabPanel("panel4a,j,four-a,)jtabPanel("panel4b","four-b"),tabPanel("panel4c",four-c")主题安装bslib包或者shinythemes包使用页面主题。thematic包可以为ggplot2lattice和baseplots提供主题,只需在服务器函数中调用thematic_shiny()o自己制作的主题,可以写好的主题放在WWw/的子文件夹下myappI-server.RI-ui.RI-wwI-mytheme.cssui<-fluidPage(theme<-bslib:bs_theme(bg="#0b3d91'fg="white"jbase_font="SourceSansPro")# theme<-shinytheme("ceruLean',)# 自制主题theme<-"mytheme.css")server<-function(input,output,session)thematic:thematic_shiny()OUtPUt$PlOt<-renderPlot(ggplot(mtcarsaes(wt,mpg)+geom_point()+geom_smooth(),res=96)ConditionalPanel创建一个面板,该面板根据JavaScript表达式的值显示和隐藏其内容。即使你不懂任何JaVaSCript,简单的比较或相等操作也非常容易做到。ui<-fluidPage(selectlnput("dataset","Dataset",c("diamonds","rock","pressure","cars"),ConditionalPanel(condition="output.nrows",checkbo×Input(',headonly"j"Onlyusefirst1000rows")server<-function(input,output,session)datasetinput<-reactive(switch(input$dataset,"rock"=rock,"pressure"=pressure,"cars"=cars)output$nrows<-reactive(nrow(datasetlnput()outputoptions(outputj"nrows"SuspendWhenHidden=FALSE)shinyApp(uijserver)HTML可以将您自己的HTML添加到Ui中。一种方法是用HTML()函数来包含HTML,用另外一种是使用Shiny提供的HTML助手。重要的标签元件有常规函数(如hl()和p(),所有其他标签都可以通过tags使用。names(tags)查看标签。ui<-fluidPage(HTML(r"(<hl>Thisisaheading<hl><pclass=,my-class">Thisissometext!<p><ul><li>Firstbullet<li><li>Secondbullet<li><ul>)")#同上ui<-fluidPage(hl(,Thisisaheading"),p("Thisissometext",class="my-class")jtags$ul(tags$li("Firstbullet"),tags$li("Secondbullet")#注意inLine=TRUE;的使用textutput()默认是生成一个完整的段落。tags$p("Youmade",tags$b("$",textoutput("amount"jinline=TRUE),"inthelast"jtextoutput("days",inline=TRUE),"days")img函数通过特殊处理才能找到图片,图片文件必须在WWW文件及在下,WWW文件和app.R脚本同路径(在同一文件下)img(src="my_image.png"jheight=72,width=72)Iibrary(Shiny)ui<-fluidPage(titlePanel("MyShinyApp"),SidebarLayout(SidebarPanel(hl("Firstleveltitle",align="center"),#标题T,居中h6("Sixthleveltitle"),p("pcreatesaparagraphoftext.",style="font-family:'times,;font-size:16pt")段落,StyLe属性支持CS5strong(',strong()makesboldtext."),#加粗em("em()createsitalicized(i.ejemphasized)text."),#斜体br(),#回车hr(),#水平分割线code(,codedisplaysyourtextsimilartocomputercode").#行内代码div("divcreatessegmentsoftextwithasimilarstyle."jstyle="color:blue")j),img(src="bigorb.png"iheight=40,width=40)#图片mainPanel(hl("Firstleveltitle",align="center"),h6("Sixthleveltitle"),p(,pcreatesaparagraphoftext.'',style="color:green;text-align:center"),strong(,strong()makesboldtext.,em(,em()createsitalicized(i.ejemphasized)text,',)jbr()>code("codedisplaysyourtextsimilartocomputercode"),div("divcreatessegmentsoftextwithasimilarstyle."style="color:blue")jimg(src="bigorb.png",height=400,width=400)#定义serverLogicserver<-function(input,output)#RuntheappLicationshinyApp(ui=ui,server=server)Shiny具有三个主要依赖项: jQuery shiny(自定义JaVaSCriPt和CSS) BOotStr叩(JaVaSCriPt和CSS)控件Shiny控件用于收集互动信息空间样式和代码可以看下面的链接httpsshiny.posit.corgallerywidgetswidget-galleryIibrary(Shiny)ui<-fluidPage(titlePanel("MyShinyApp"),SidebarLayout(sidebarPanel(#行fluidRow(#列COIUlnn(3,#CoIUmn的网格宽度(必须在1到12之间)h3("Buttons"),actionButton("action",label="Action"),#点山br(),br(),downloadButton("downloadData',"Download"),br(),br(),submitButton("Submit,)提交h3("Singlecheckbox"),checkboxinput("checkbox".,label="ChoiceA",value=TRUE),#函个勾选框#另起一列COlUnIn(3,CheckboxGroupInput("checkGroup",label=h3("Checkboxgroup"),choices=list("Choice1"=1,"Choice2"=2,"Choice3"=3),selected=1),#多选框dateinput("date",label=h3("Dateinput"),value="2024-01-01")#日期选择框),#另起一行fluidRow(COlUnln(3,dateRange!nput("dates",label=h3("Daterange")#日期范围选择框),COlUnln(3,filelnput("filelabel=h3("Fileinput")#文件选择框),COlUnIn(3,h3("Helptext"),helpText("Note:helptextisn'tatruewidget,"butitprovidesaneasywaytoaddtextto"j"accompanyotherwidgets.,),COlUnIn(3,numericinput("num"label=h3("Numericinput"),value=1)#数字输入框),fluidRow(COlUmn(3,radioButtons("radio",label=h3("Radiobuttons")jchoices=list("Choice1"=1,"Choice2"=2,"Choice3"=3),selected=I)#单选框),COlUmn(3,selectlnput("select",label=h3("Selectbox"),choices=list("Choice1"=1,"Choice2"=2,"Choice3"=3),selected=I)#卜.拉选择框),column(3jsliderinput("slideri",label=h3("Sliders"),min=0,max=100,value=50,animate=animationoptions(interval=300,loop=TRUE),#拖动选择sliderlnput(',slider2",",min=0,max=100,value=c(25,75)#拖动选择),column(3jtext:叩Ut:(“text”,label=h3(,Textinput"),value="Entertext.文本输入框),mainPanel()# 定义serverLogicserver<-function(input,output)# RuntheappLicationshinyApp(ui=Ui,server=server)# 按钮复位# https:/hadLey.shinyappsoms-update-resetui<-fluidPage(sliderlnput("xl"j"xl"j0,min=-10,max=10),sliderlnput(,'x2","x2",0,min=-104max=10),sliderlnput("×3","×3",0,min=-104max=10),actionButton("reset","Reset")server<-function(input,output,session)ObserveEvent(input$resetUPdateSlider工nput(input工d="xl",value=0)UpdateSliderInput(inputld="x2",value=0)UPdateSIider工叩ut(inPUtId="x3",value=0)shinyApp(ui=ui,server=server)控件输入输入函数:textinput,passwordinput,IextAreaInput,sliderinput如果你想确保文本具有某些属性,你可以使用validate()oIibrary(Shiny)ui<-fluidPage(theme<-bslib:bs_theme(bootswatch="cerulean"),titlePanel("MyShinyApp")jSidebarLayout(sidebarPanel(actionButton("action,jlabel="Action"),mainPanel(VerbatimTextOutput("value")# 定义serverLogicserver<-function(input,output)OUtPUt$ValUe<-renderPrint(input$action)输出函数ui中输出函数:Output,htmlutput,imageutput,plotoutput,tableutput,dataTableOutput,textoutput,uiutput,VerbatimTextOutputserver中render函数render,renderimage,renderPlot,renderPrint,renderTable,renderTe×t,renderUI,renderPrint每个render*函数都有唯一参数。在render函数之内的代码,一旦控件的某个值改变,那么,Shiny会重新执行render内的所有代码块。uiOutput:动态UI输出PlotlyOutput:使用plotly包中的函数动态输出renderUI:动态Ul输入renderPlotly:使用PlOtIy包中的函数动态输出Iibrary(Shiny)ui<-fluidPage(titlePanel("字体大小,字体颜色”),sidebarLayout(sidebarPanel(sliderinput("psize",label=h3("字体大小调节”),min=6,max=100,value=10),#拖动选择,hr(),radioButtons("pcolor",label=h3("字体颜选择色”),choices=list("red"="red","blue"="blue","green"="green")?selected="blue"),mainPanel(p("123",styles=,colors,),htmlOutput("colors"),textutput("sizes")# 定义serverLogicserver<-function(input,output)OUtPUt$COIorS<-renderText(paste(,"color:'iinput$PCoIOP,'"')OutputSsizes<-renderText(paste('"front-size:,input$psize>,pt",)# RuntheQppLicationShinyAPP(Ui,server)动态调整按钮调整按钮显示文本ui<-fIuidPage(numericinput("n,"Simulations",10),actioButton("simulate","Simulate")server<-function(input,OUtPlit,session)ObserveEvent(inputSnjlabel<-paste0("Simulate”,input$n,times")UpdateActionButton(inputld="simulate",label=label)shinyApp(ui=ui,server=server)UPdateSeIeCt工nput()只有在所有output和observer都运行后才会产生影响。ui<-fluidPage(#创建三个选择框和一个输出表selectlnput("territory","Territory"jchoices=UniqUe(SaleS$TERR工TORY),selectinput("customername","Customer",choices=NULL),#CUStOmernQme公门动牛.成,所以Choices=NULLselectinput("ordernumber","Ordernumber",choices=NULL),ordernumber公门动生成,所以choices=NULLtableutput("data")server<-function(input,output,session)territory<-reactive(filter(sales,TERRITORY=input$territory)#包含SaleS与所选territory匹配的行ObserveEvent(territory()ichoices<-unique(territory()$CUSTOMERNAME)UpdateSelectInput(inputld="customername"jchoices=choices)#今巧territory()更;女时,都会更新inputfcustomername选择框中choices的列衣customer<-reactive(req(input$customername)filter(territory()jCUSTOMERNAME=input$CUStOmername)#包含territory。与所选CUStomernQme匹西己的行ObserveEvent(customer(),choices<-unique(customer()$ORDERNUMBER)UpdateSelectInput(inputld="ordernumber",choices=choices)#每当customer()更改时,都会更新input$ordernumber选择框中choices的列表OutputSdata<-renderTable(req(input$ordernumber)customer()%>%filter(ORDERNUMBER=input$ordernumber)%>%select(Quantityordered,priceeach,productcode)客户端的非输入数据在服务器端,Shiny应用程序使用输入对象从客户端Web浏览器接收用户输入。输入中的值由客户端网页上的Ul对象设置。还有一些非输入值(从某种意义上说,用户不会通过UI组件输入这些值)存储在名为SessionJclientData的对象中。这些值包括URL、像素比率(用于高分辨率“视网膜”显示器)、输出对象的隐臧状态以及打印输出的高度和宽度。Iibrary(Shiny)ui<-PageUIithSidebar(headerPanel("ShinyClientData"),sidebarPanel(sliderinput("obs'"Numberofobservations:",min=0,max=1000,value=500),mainPanel(h3("clientDatavalues,)jVerbatimTextoutputCclientdataText"),plotoutput("myplot")server<-function(input,output,session)# StoreinaconvenienceVariabLecdata<-session$clientData# VaLuesfromcdatareturnedastextOutputJclientdataText<-renderText(cnames<-names(cdata)allvalues<-lapply(cnames,function(name)paste(namecdataname>sep=,=")paste(allvaluesjcollapse="n")# AhistogramOutputSmyplot<-renderPlot(hist(rnorm(input$obs),main="GeneratedinrenderPlot()")!)shinyApp(uijserver)发布分享分享R文件将app.R文件放在app文件夹中,启动如下:Iibrary(Shiny)runApp("app")runUrl文件夹压缩为zip格式可以在网上直接下载并启动appIibrary(Shiny)runUrl("<theweblink>u)runGitHubIibrary(Shiny)runGitHub("html2R,j,alandipert")通过网页进行分享shinyapps.ioAMMWWNBMWtM,i,349一https:/alandipert.shinyapps.io/html2r服务器上安装ShinyServer参考1. Shiny篇(7)分享App-知乎()2. WelcomeMasteringShiny(mastering-shiny.org)3. Shiny-LearnaboutyouruserwithSessionSclientData(posit.co)4. Chapter6Layout,themes,HTMLMasteringShiny(mastering-shiny.org)5. Shiny-BuildadynamicUIthatreactstouserinput(posit.co)6. R-Shiny10DynamicUI-知乎()