r语言r-shiny_使用Shiny和R构建您的第一个Web应用程序仪表板

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 dash) is Shiny. 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漏掉了,直到破折号 )是ShinyShiny是一个R软件包,可以很容易地从R直接构建交互式Web应用程序。 仪表板之所以受欢迎,是因为它们很好地帮助企业从现有数据中获得洞察。

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

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

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

The packages you need must be downloaded separately, and installed 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 recommendation.csv 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 recommendation.csv file into your current R session:

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

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

    打开此链接— Recommendation.csv 并将其(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. shinydashboard is an R package whose job is to make it easier, as the name suggests, to build dashboards with Shiny.

我们不仅将其仅使用Shiny还将其与Shinydashboard结合在一起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 running the shiny app. 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 my Github. If you are interested in Shiny, you can learn more from DataCamp’s Building Web Applications in R with Shiny Course.

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

翻译自: https://www.freecodecamp.org/news/build-your-first-web-app-dashboard-using-shiny-and-r-ec433c9f3f6c/

r语言r-shiny

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/394554.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

RHEL5.8配置开机自动挂载磁盘

Linux环境中可以通过fstab来设置自动挂载磁盘或者共享存储&#xff0c;操作如下&#xff1a; fstab配置文件路径&#xff1a;/etc/fstab 每行代表一个存储位置。 [rootappsrv01 ~]# cat /etc/fstab LABEL/ / ext3 defaults 1…

909计算机基础大纲,《计算机应用基础》(专科)考试大纲

《计算机应用基础》(专科)考试大纲《计算机应用基础》考试大纲考试对象&#xff1a;《计算机应用基础》考试大纲适用于网络教育所有专业的高中起点专科学生。 考试教材&#xff1a;《全国计算机等级考试一级MS Office教程》(2004版)&#xff0c;南开大学出版社 课程学时&#x…

模板变量,过滤器和静态文件引用

模板变量&#xff0c;过滤器和静态文件引用 模板路径 Djiango先到settings里面找templates下的DIRS查看是否有路径&#xff0c;也是从上往下依次寻找&#xff0c;找到就返回。如果DIRS没有&#xff0c;就到APP_DIRS里面寻找。但是APP要先在INSTALLED_APPS里面进行注册然后根据I…

antd option宽度自适应_WordPress文章中添加自适应宽度的表格——墨涩网

WordPress文章中添加自适应表格&#xff0c;前面写文章的时候需要用到表格来表达阵列信息&#xff0c;但是在WordPress添加表格不想是在office中那样方便&#xff0c;需要借助插件或者代码才可以实现&#xff0c;今天分享一个不需要安装插件纯代码实现WordPress文章中添加自适应…

Go语言程序记录日志

许多软件系统运行中需要日志文件。Go语言程序中&#xff0c;输出日志需要使用包"log"&#xff0c;编写程序十分简单。 像Java语言程序&#xff0c;输出日志时&#xff0c;往往需要使用开源的软件包来实现&#xff0c;编写程序稍微复杂一些。 Go语言的包"log&quo…

如何让代码更易于维护_如何轻松地使您的网站更易于访问

如何让代码更易于维护by Jaroslav Vaňkt通过JaroslavVaňkt 如何轻松地使您的网站更易于访问 (How you can easily make your website more accessible) As a designer, developer, or even product manager, you have thousands of responsibilities. Every project require…

计算机安全概论论文,计算机安全探讨论文毕业论文(7篇).doc

计算机安全探讨论文毕业论文(7篇)计算机安全探讨论文毕业论文(7篇)计算机安全探讨论文毕业论文(7篇)预读: 第一篇:终端计算机安全检查技术研究【摘要】信息安全保密管理工作的重点和计算机终端检查的难点,促进了计算机安全检查技术的发展.本文回顾了终端检查技术经历的三个阶段…

OO第一单元总结

OO第一单元总结 第一次作业总结 这是我第一次接触Java和面向对象思想&#xff0c;最一开始&#xff0c;我建立了简单的类和对象的概念&#xff0c;多亏了第一次作业难度和复杂度较低&#xff0c;我才没有崩掉hhh。 第一次作业我只分了三个类&#xff0c;一个main&#xff0c;一…

接口开发指的是什么_企业在什么情况下要选择定制开发软件

软件定制开发是指软件开发商依据我们的需求停止量身定制的开发&#xff0c;软件定制开发相关于单纯产品的施行周期长、本钱高、风险大。假如根据定制开发的工作量或水平来分&#xff0c;我们能够分为完整定制开发和局部定制开发&#xff0c;完整定制开发是指软件开发公司依据我…

python2x 安装 psutil

安装psutil模块&#xff1a; wget https://pypi.python.org/packages/source/p/psutil/psutil-2.0.0.tar.gz --no-check-certificatetar -zxvf psutil-2.0.0.tar.gzcd psutil-2.0.0python setup.py install转载于:https://www.cnblogs.com/yingdiblog/p/7347325.html

c++编码风格指南_带回家的编码挑战的基本指南

c编码风格指南by Jane Philipps简菲利普斯 带回家的编码挑战的基本指南 (The Essential Guide to Take-home Coding Challenges) 介绍 (Introduction) Hi, I’m Jane. I wrote this guide because I want to help others with non-traditional backgrounds succeed on take-ho…

计算机没有搜索筛选功能,EXCEL中筛选工具怎么没有搜索功能

EXCEL中筛选工具怎么没有搜索功能卡饭网本站整理2018-04-01excel是一款数据处理工具&#xff0c;可以在众多的数据中找到想要的经过处理之后的数据&#xff0c;而最直接方便的功能就是筛选。请阅读下文&#xff0c;了解如何对数据进行筛选。如下图所示的学生成绩中&#xff0c;…

谈谈最短路径

最近遇到一些个问题&#xff0c;有关最短路径算法&#xff0c;又称A算法转载于:https://www.cnblogs.com/swell/p/6108850.html

51nod 1851 俄罗斯方块(思维题)

分析&#xff1a;假设n>m&#xff0c;m为1,2单独讨论下&#xff0c;否则可以用第二行第一个把所有黑块搞到2x2的格子里&#xff0c;不断用凸出来的那个角一列一列把黑的变白就行了。然后只要黑色有偶数块都可以构造出来。复杂度O(nm) #include <iostream> #include &l…

python发邮件详解_python实现发送邮件详解

[Python]代码#_*_encoding:utf-8_*_#script for python3.2#-------------------------------------------------------------------------------# Name: 发送邮件# Purpose:## Author: QiuChangJie## Created: 10/09/2012# Copyright: (c) cj.qiu 2012# Licence: #------------…

gprof, Valgrind and gperftools - an evaluation of some tools for application level CPU profiling on

2019独角兽企业重金招聘Python工程师标准>>> In this post I give an overview of my evaluation of three different CPU profiling tools: gperftools, Valgrind and gprof. I evaluated the three tools on usage, functionality, accuracy and runtime overhead…

xp计算机属性打不开,xp系统我的电脑右键属性打不开怎么办

在使用xp系统过程中,我们经常需要打开“我的电脑”右键属性,查看系统信息以及进行虚拟内存、性能方面的设置,不过有深度技术ghost xp sp3纯净版用户右键点击我的电脑,发现右键菜单中的“属性”打不开,出现这个问题通常是注册表禁用了这个属性,下面小编跟大家介绍xp系统我的电脑…

状态机学习(二)解析INI文件

题目来自<系统程序员成长计划> 作者:李先静. 状态变化如下 #include <string> #include <iostream> using namespace std;string s "[GRP]\n\ name def \n\ data 2016.11.29 \r\n\ ; this is a comment \r\n\ str this is a test \n\ [zhangshan]…

接口之用例编写、验证

一、用Excel编写用例&#xff08;xlsx格式&#xff09; 截图仅供参考&#xff0c;实际用例编写需要根据实际情况来。 二、用例加载、验证 1、数据的加载 import xlrd,xlwt #python操作excel主要用到xlrd和xlwt这两个库&#xff0c;即xlrd是读excel&#xff0c;xlwt是写excel的库…

计算机二级word真题书娟,计算机二级word试题.docx

PAGEPAGE # / 80Word试题在考生文件夹下打开文档 word.docx &#xff0c;按照要求完成下列操作并以该文件名( word.docx )保存文档。某高校为了使学生更好地进行职场定位和职业准备&#xff0c;提高就业能力&#xff0c;该校学工处将于2013 年 4月 29 日(星期五) 19:30-21:30 在…