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.pswp.cn/news/394554.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/394554.shtml
英文地址,請注明出處:http://en.pswp.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 在…