博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
r语言r-shiny_使用Shiny和R构建您的第一个Web应用程序仪表板
阅读量:2521 次
发布时间:2019-05-11

本文共 10978 字,大约阅读时间需要 36 分钟。

r语言r-shiny

by AMR

通过AMR

使用Shiny和R构建您的第一个Web应用程序仪表板 (Build your first web app dashboard using Shiny and R)

One of the beautiful gifts that R has (that Python missed,until ) is . Shiny is an R package that makes it easy to build interactive web apps straight from R. Dashboards are popular since they are good in helping businesses make insights out of the existing data.

R拥有的漂亮礼物之一(Python漏掉了,直到 )是 。 Shiny是一个R软件包,可以很容易地从R直接构建交互式Web应用程序。 仪表板之所以受欢迎,是因为它们很好地帮助企业从现有数据中获得洞察。

In this post, we will see how to leverage Shiny to build a simple sales revenue dashboard. You will need .

在这篇文章中,我们将看到如何利用Shiny构建一个简单的销售收入仪表板。 您将需要

在R中加载软件包 (Loading packages in R)

The packages you need must be downloaded separately, and using R. All the packages listed below can be directly installed from CRAN, you can choose which CRAN mirror to use. Package dependencies will also be downloaded and installed by default.

您需要的软件包必须单独下载,并使用R 。 可以从CRAN直接安装下面列出的所有软件包,您可以选择要使用的CRAN镜像。 默认情况下,还将下载和安装软件包依赖项。

Once the packages are installed, you need to load them into your R session. The library and require commands are used and, again, package dependencies are also loaded automatically by R.

安装软件包后,您需要将它们加载到R会话中。 使用了library和require命令,并且包依赖关系也由R自动加载。

# load the required packageslibrary(shiny)require(shinydashboard)library(ggplot2)library(dplyr)

样本输入文件 (Sample input file)

As a dashboard needs an input data to visualize, we will use as an example of input data to our dashboard. As this is a .csv file, the read.csv command was used. The first row in the .csv is a title row, so header=T is used. There are two ways you can get the file into your current R session:

由于仪表板需要输入数据才能可视化,因此我们将使用作为向我们的仪表板输入数据的示例。 由于这是一个.csv文件,因此使用了read.csv命令。 .csv中的第一行是标题行,因此使用header = T。 您可以通过两种方式将文件放入当前的R会话中:

  1. Open this link — and save it (Ctrl+S) in your , where this R code is saved. Then the following code will work perfectly.

    打开此链接— 并将其(Ctrl + S) 保存在 ,该R代码存储在该中。 然后,以下代码将完美运行。

recommendation <- read.csv('recommendation.csv',stringsAsFactors = F,header=T)head(recommendation)       Account Product Region Revenue1    Axis Bank     FBB  North    20002         HSBC     FBB  South   300003          SBI     FBB   East    10004        ICICI     FBB   West    10005 Bandhan Bank     FBB   West     2006    Axis Bank    SIMO  North     200

2. Instead of reading the .csv from your local computer, you can also read it from a URL (web) using the same function read.csv. Since this .csv is already uploaded on my Github, we can use that link in our read.csv to read the file.

2.除了从本地计算机读取.csv之外,您还可以使用相同的read.csv函数从URL(Web)读取它 由于此.csv已经上传到我的Github上,因此我们可以在read.csv中使用该链接来读取文件。

recommendation <- read.csv('https://raw.githubusercontent.com/amrrs/sample_revenue_dashboard_shiny/master/recommendation.csv',stringsAsFactors = F,header=T)head(recommendation)       Account Product Region Revenue1    Axis Bank     FBB  North    20002         HSBC     FBB  South   300003          SBI     FBB   East    10004        ICICI     FBB   West    10005 Bandhan Bank     FBB   West     2006    Axis Bank    SIMO  North     200

闪亮的概述 (Overview of Shiny)

Every Shiny application has two main sections: UI and Server. UI contains the code for front-end like buttons, plot visuals, tabs and so on. Server contains the code for back-end like data retrieval, manipulation, and wrangling.

每个Shiny应用程序都有两个主要部分: UIServerUI包含前端代码,如按钮,绘图视觉效果,选项卡等。 服务器包含用于后端的代码,例如数据检索,操作和整理。

Instead of simply using only Shiny, we couple it with . shinydashboard is an R package whose job is to make it easier, as the name suggests, to build dashboards with Shiny.

我们不仅将其仅使用Shiny , 其与结合 。 Shinydashboard是一个R包,其工作就是使它更容易使用Shiny来构建仪表板,顾名思义。

创建填充的仪表板:UI (Creating a populated dashboard: UI)

The UI part of a Shiny app built with shinydashboard has 3 basic elements wrapped in the dashboardPage() command. The simplest Shiny code with shinydashboard

使用Shinydashboard构建的Shiny应用程序的UI部分在dashboardPage()命令中包含3个基本元素。 最简单的带有Shinydashboard的 Shiny代码

## app.R ##library(shiny)library(shinydashboard)ui <- dashboardPage(  dashboardHeader(),  dashboardSidebar(),  dashboardBody())server <- function(input, output) { }shinyApp(ui, server)

gives this app

给这个程序

Let us populate dashboardHeader() and dashboardSidebar(). The code contains comments, prefixed with #.

让我们填充dashboardHeader()dashboardSidebar() 。 该代码包含以#开头的注释。

#Dashboard header carrying the title of the dashboardheader <- dashboardHeader(title = "Basic Dashboard")  #Sidebar content of the dashboardsidebar <- dashboardSidebar(  sidebarMenu(    menuItem("Dashboard", tabName = "dashboard", icon = icon("dashboard")),    menuItem("Visit-us", icon = icon("send",lib='glyphicon'),              href = "https://www.salesforce.com")  ))

The UI elements that we would like to show in our dashboard populate dashboardPage() . Since the example is a sales revenue dashboard, let us show three Key Performance Indicator (KPI) boxes on the top that represent a quick summary, followed by two box plots for a detailed view.

我们希望在仪表dashboardPage()显示的UI元素填充dashboardPage() 。 由于该示例是销售收入仪表板,因此让我们在顶部显示三个关键绩效指标(KPI)框,这些框代表一个快速摘要,然后是两个框图以获取详细视图。

To align these elements, one by one, we define them inside fluidRow().

为了将这些元素一一对齐,我们在fluidRow()内部定义它们。

frow1 <- fluidRow(  valueBoxOutput("value1")  ,valueBoxOutput("value2")  ,valueBoxOutput("value3"))frow2 <- fluidRow(   box(    title = "Revenue per Account"    ,status = "primary"    ,solidHeader = TRUE     ,collapsible = TRUE     ,plotOutput("revenuebyPrd", height = "300px")  )  ,box(    title = "Revenue per Product"    ,status = "primary"    ,solidHeader = TRUE     ,collapsible = TRUE     ,plotOutput("revenuebyRegion", height = "300px")  ) )# combine the two fluid rows to make the bodybody <- dashboardBody(frow1, frow2)

In the above code, valueBoxOutput() is used to display the KPI information. valueBoxOutput() and plotOutput() are written in the Server part, which is used in the UI part to display a plot. box() is a function provided by shinydashboard to enclose the plot inside a box that has features like title, solidHeaderand collapsible. Having defined two fluidRow() functions individually for the sake of modularity, we combine both of them in dashbboardBody().

在上面的代码中, valueBoxOutput()用于显示KPI信息。 valueBoxOutput()plotOutput()编写在Server部分中,该部分在UI部分中用于显示绘图。 box()shinydashboard提供的函数,用于将图封闭在具有titlesolidHeadercollapsible类的功能的solidHeader 。 为了模块化,分别定义了两个fluidRow()函数,我们将它们都合并在dashbboardBody()

Thus we can complete the UI part, comprising header, sidebar, and page, with the code below:

因此,我们可以使用以下代码完成UI部分,包括标题,侧边栏和页面:

#completing the ui part with dashboardPageui <- dashboardPage(title = 'This is my Page title', header, sidebar, body, skin='red')

The value of title in dashboardPage() is the title of the browser page/tab, while the title defined in dashboardHeader() is visible as the dashboard title.

的值titledashboardPage()是浏览器页面/选项卡的标题,而在限定的标题dashboardHeader()是作为仪表盘标题可见。

创建填充的仪表板:服务器 (Creating a populated dashboard: Server)

With the UI part over, we will create the Server part where the program and logic behind valueBoxOutput() and plotOutput() are added with renderValueBox() and renderPlot() respectively. These are enclosed inside a server function , with input and output as its parameters. Values inside inputare received from UI (like textBox value, Slider value). Values inside output are sent to UI (like plotOutput, valueBoxOutput).

UI部分结束后,我们将创造一个程序,背后的逻辑服务器部分valueBoxOutput()plotOutput()被添加renderValueBox()renderPlot()分别。 它们包含在server function ,并以inputoutput作为其参数。 input内部的值是从UI接收的(例如textBox值, Slider值)。 output中的值将发送到UI (例如plotOutputvalueBoxOutput )。

Below is the complete Server code:

以下是完整的服务器代码:

# create the server functions for the dashboard  server <- function(input, output) {   #some data manipulation to derive the values of KPI boxes  total.revenue <- sum(recommendation$Revenue)  sales.account <- recommendation %>% group_by(Account) %>% summarise(value = sum(Revenue)) %>% filter(value==max(value))  prof.prod <- recommendation %>% group_by(Product) %>% summarise(value = sum(Revenue)) %>% filter(value==max(value))#creating the valueBoxOutput content  output$value1 <- renderValueBox({    valueBox(      formatC(sales.account$value, format="d", big.mark=',')      ,paste('Top Account:',sales.account$Account)      ,icon = icon("stats",lib='glyphicon')      ,color = "purple")    })  output$value2 <- renderValueBox({     valueBox(      formatC(total.revenue, format="d", big.mark=',')      ,'Total Expected Revenue'      ,icon = icon("gbp",lib='glyphicon')      ,color = "green")    })output$value3 <- renderValueBox({    valueBox(      formatC(prof.prod$value, format="d", big.mark=',')      ,paste('Top Product:',prof.prod$Product)      ,icon = icon("menu-hamburger",lib='glyphicon')      ,color = "yellow")     })#creating the plotOutput content  output$revenuebyPrd <- renderPlot({    ggplot(data = recommendation,            aes(x=Product, y=Revenue, fill=factor(Region))) +       geom_bar(position = "dodge", stat = "identity") + ylab("Revenue (in Euros)") +       xlab("Product") + theme(legend.position="bottom"                               ,plot.title = element_text(size=15, face="bold")) +       ggtitle("Revenue by Product") + labs(fill = "Region")  })output$revenuebyRegion <- renderPlot({    ggplot(data = recommendation,            aes(x=Account, y=Revenue, fill=factor(Region))) +       geom_bar(position = "dodge", stat = "identity") + ylab("Revenue (in Euros)") +       xlab("Account") + theme(legend.position="bottom"                               ,plot.title = element_text(size=15, face="bold")) +       ggtitle("Revenue by Region") + labs(fill = "Region")  })}

So far, we have defined both essential parts of a Shiny app — UI and Server. Finally, we have to call/run the Shiny, with UI and Server as its parameters.

到目前为止,我们已经定义了一个闪亮的应用程序的两个关键部分- UI服务器 。 最后,我们必须调用/运行Shiny UIServer作为其参数。

#run/call the shiny appshinyApp(ui, server)Listening on http://127.0.0.1:5101

The entire R file has to be saved as app.R inside a folder before . Also remember to put the input data file (in our case, recommendation.csv) inside the same folder as app.R. While there is another valid way to structure the Shiny app with two files ui.R and server.R(optionally, global.R), it has been ignored in this article for the sake of brevity since this is aimed at beginners.

之前 ,必须将整个R文件另存为app.R在一个文件夹 。 还要记住,将输入数据文件(在我们的示例中为app.R recommendation.csv)放入与app.R相同的文件夹中。 尽管还有另一种有效的方法来构建具有两个文件ui.Rserver.R (可选地, global.R )的Shiny应用程序,但为简洁起见,本文中已将其忽略,因为它是针对初学者的。

Upon running the file, the Shiny web app will open in your default browser and look similar to the screenshots below:

运行文件后, Shiny Web应用程序将在默认浏览器中打开,外观类似于以下屏幕截图:

Hopefully, at this stage, you have this example Shiny web app up and running. The code and plots used here are available on . If you are interested in Shiny, you can learn more from DataCamp’s .

希望在此阶段,您可以启动并运行此示例Shiny Web应用程序。 上提供了此处使用的代码和绘图。 如果您对Shiny感兴趣,可以从DataCamp的了解更多信息。

翻译自:

r语言r-shiny

转载地址:http://wcgwd.baihongyu.com/

你可能感兴趣的文章
【吵架不能吵半截】
查看>>
电子书下载:Silverlight 4: Problem – Design – Solution
查看>>
为Vmware硬盘减肥瘦身
查看>>
YTT的提问以及由此引出的未来规划之思考
查看>>
QTP8.2--安装流程
查看>>
一步一步点亮Led
查看>>
POJ 3630 Phone List [Trie]
查看>>
springmvc 可以设置 <welcome-file>test.do</welcome-file>
查看>>
多Form界面控件状态变化问题分析
查看>>
面试记-(1)
查看>>
压力测试 相关
查看>>
MyBatis 通过 BATCH 批量提交
查看>>
android update automatically ( android 自动升级)
查看>>
session cookie
查看>>
POJ 1222 EXTENDED LIGHTS OUT(翻转+二维开关问题)
查看>>
【BZOJ-4059】Non-boring sequences 线段树 + 扫描线 (正解暴力)
查看>>
几种简单的负载均衡算法及其Java代码实现
查看>>
TMS3705A PCF7991AT 线路图
查看>>
安装Hadoop
查看>>
[BZOJ2282][Sdoi2011]消防
查看>>