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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,下面是一个简单的例子,用于预测肿瘤患者的未来2年生存概率和未来存活时间。代码中用到了shiny库和survival库。 首先,我们需要准备好数据。假设我们的数据是一个csv文件,有以下几列:性别(sex)、年龄(age)、是否接受放疗(radiation)、是否接受化疗(chemotherapy)、手术方式(surgery)、肿瘤扩散程度(extension)、肿瘤是否转移(met)、是否存活(status)和存活时间(time)。 接下来,我们需要加载所需的库,并读取数据: ```R library(shiny) library(survival) data <- read.csv("data.csv") ``` 然后,我们需要拟合Cox比例风险模型,用于预测生存概率和生存时间。在这个例子中,我们将使用所有变量来拟合模型: ```R fit <- coxph(Surv(time, status) ~ sex + age + radiation + chemotherapy + surgery + extension + met, data = data) ``` 接下来,我们需要编写交互式应用程序UI界面。在这个例子中,我们将使用shiny库的fluidPage函数来构建UI界面。我们将添加一个标题,以及一些滑块和下拉框,用于选择预测模型所需的变量: ```R ui <- fluidPage( titlePanel("肿瘤患者生存预测"), sidebarLayout( sidebarPanel( sliderInput("age", "年龄", min = 18, max = 100, value = 50), selectInput("sex", "性别", choices = c("男", "女")), selectInput("radiation", "是否接受放疗", choices = c("是", "否")), selectInput("chemotherapy", "是否接受化疗", choices = c("是", "否")), selectInput("surgery", "手术方式", choices = c("开刀", "化疗", "放疗")), selectInput("extension", "肿瘤扩散程度", choices = c("低", "中", "高")), selectInput("met", "是否转移", choices = c("是", "否")) ), mainPanel( h4("2年生存概率:"), verbatimTextOutput("prob"), h4("未来存活时间:"), verbatimTextOutput("time") ) ) ) ``` 在UI界面中,我们使用了sliderInput和selectInput函数来创建滑块和下拉框。这些控件将在交互式应用程序中允许用户选择变量的值。 接下来,我们需要编写服务器端的代码。在这个例子中,我们将使用shiny库的renderText函数来生成交互式应用程序的输出。我们将使用predict函数来预测生存概率和生存时间,然后将结果输出到UI界面中。 ```R server <- function(input, output) { output$prob <- renderText({ newdata <- data.frame( sex = ifelse(input$sex == "男", 1, 0), age = input$age, radiation = ifelse(input$radiation == "是", 1, 0), chemotherapy = ifelse(input$chemotherapy == "是", 1, 0), surgery = input$surgery, extension = input$extension, met = ifelse(input$met == "是", 1, 0) ) prob <- predict(fit, newdata, type = "survival")[2] paste0(round(prob * 100, 2), "%") }) output$time <- renderText({ newdata <- data.frame( sex = ifelse(input$sex == "男", 1, 0), age = input$age, radiation = ifelse(input$radiation == "是", 1, 0), chemotherapy = ifelse(input$chemotherapy == "是", 1, 0), surgery = input$surgery, extension = input$extension, met = ifelse(input$met == "是", 1, 0) ) time <- predict(fit, newdata, type = "expected")[1] paste0(round(time, 2), "年") }) } ``` 在服务器端的代码中,我们使用了predict函数来预测生存概率和生存时间。我们首先从UI界面中获取用户选择的变量值,然后将这些值组成一个新的数据框,用于预测模型。我们使用type参数来指定需要计算的预测结果类型。在这个例子中,我们分别计算2年生存概率和未来存活时间的期望值。最后,我们使用paste0函数将预测结果输出到UI界面中。 最后,我们需要将UI界面和服务器端的代码整合到一起,创建交互式应用程序: ```R shinyApp(ui, server) ``` 这样就完成了肿瘤患者生存预测的交互式应用程序。用户可以通过滑块和下拉框选择变量值,程序将根据预测模型预测2年生存概率和未来存活时间,并将结果输出到UI界面中。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值