R编程中的闪亮包
包是组织工作并与他人共享的适当方式。 R 编程语言中的包是 R 函数、编译代码和示例数据的集合。它们存储在 R 环境中名为“库”的目录下。默认情况下,R 在安装过程中会安装一组包。 R 中最重要的包之一是Shiny包。 Shiny是一个 R 包,可以轻松地直接从 R 构建交互式 Web 应用程序。它有助于在网页上托管独立应用程序或将它们嵌入 R Markdown 文档或构建仪表板。还可以使用 CSS 主题、htmlwidget 和 JavaScript 操作来扩展 Shiny 应用程序。
闪亮的包安装在R语言
要在 R 编程中使用包,必须首先安装包。可以使用命令install.packages(“packagename”)完成此任务。要安装整个Shiny包,请输入:
install.packages("shiny")
要直接从 GitHub 安装最新的开发版本,请运行以下命令:
if (!require("remotes"))
install.packages("remotes")
remotes::install_github("rstudio/shiny")
R 语言示例中的闪亮包
Shiny 包中的重要动词函数
- fluidPage():它创建一个具有流体布局的页面。流畅的页面布局由行组成,而行又包括列。行的存在是为了确保它们的元素出现在同一行上,而列的存在是为了定义 12 单位宽的网格中的水平空间量。流体页面实时缩放其组件以填充所有可用的浏览器宽度。
Syntax:
fluidPage(…, title = NULL, theme = NULL)
Parameter | Description |
---|---|
… | Elements to include within the page. |
title | The browser window title. |
theme | Alternative Bootstrap stylesheet. |
例子:
这是一个基本的闪亮应用程序模板。
R
# import shiny package
library(shiny)
# define a page with fluid layout
ui <- fluidPage(h1("GeeksforGeeks article on shiny package in R"),
p(style = "font-family:Impact", "My first shiny app")
)
server <- function(input, output) {}
shinyApp(ui = ui, server = server)
R
# import shiny package
library(shiny)
# define fluid page layout
ui <- fluidPage(
sliderInput(inputId = "num",
label = "Choose a number",
value = 10, min = 1, max = 1000),
plotOutput("hist")
)
server <- function(input, output)
{
output$hist <- renderPlot({
hist(rnorm(input$num))
})
}
# create shiny app object
# using shinyApp
shinyApp(ui = ui, server = server)
R
# import shiny package
library(shiny)
# define fluid page layout
ui <- fluidPage(
textInput(inputId = "num", label = "Choose a number",
value = "", width = 100, placeholder = NULL),
plotOutput("hist"),
verbatimTextOutput("stats")
)
server <- function(input, output)
{
# use reactive to create
# a reactive expression
data <- reactive({rnorm(input$num)})
output$hist <- renderPlot({hist(data())})
output$stats <- renderPrint({summary(data())})
}
# create shiny app object
# using shinyApp
shinyApp(ui = ui, server = server)
R
# import shiny package
library(shiny)
# define fluid page layout
ui = fluidPage(
textInput(inputId = "num",
label = "Enter a numeric value", value = "10"),
actionButton("button", "Calculate"),
column(8, tableOutput("table"))
)
server = function(input, output)
{
# Take an action every time button is pressed
observeEvent(input$button, {
cat("Showing", input$num, "rows\n")
})
# Take a reactive dependency
# on input$num, but not on any
# of the stuff inside the function
df <- eventReactive(input$button, {
head(cars, input$num)
})
output$table <- renderTable({
df()
})
}
# create shiny app object
# using shinyApp
shinyApp(ui, server)
R
# import shiny package
library(shiny)
# define fluid page layout
ui <- fluidPage(
sliderInput(inputId = "num",
label = "Choose a number",
value = 25, min = 1, max = 100),
actionButton(inputId = "go",
label = "Update"),
plotOutput("hist")
)
server <- function(input, output)
{
data <- eventReactive(input$go, {
rnorm(input$num)
})
output$hist <- renderPlot({
hist(data())
})
}
# create shiny app object
# using shinyApp
shinyApp(ui = ui, server = server)
R
# import shiny package
library(shiny)
# define fluid page layout
ui <- fluidPage(
sliderInput("obs", "Number of observations", 0, 1000, 500),
actionButton("goButton", "Go!", class = "btn-success"),
plotOutput("distPlot")
)
server <- function(input, output)
{
output$distPlot <- renderPlot({
input$goButton
dist <- isolate(rnorm(input$obs))
hist(dist)
})
}
# create shiny app object
# using shinyApp
shinyApp(ui, server)
R
# import shiny package
library(shiny)
# define fluid page layout
ui <- fluidPage(
checkboxGroupInput("icons", "Choose icons:",
choiceNames =
list(icon("dog"), icon("cat"),
icon("fish"), icon("bug")),
choiceValues =
list("dog", "cat", "fish", "bug")),
textOutput("txt")
)
server <- function(input, output, session)
{
output$txt <- renderText({
icons <- paste(input$icons, collapse = ", ")
paste("You chose", icons)
})
}
# create shiny app object
# using shinyApp
shinyApp(ui = ui, server = server)
R
# import shiny package
library(shiny)
# define fluid page layout
ui <- fluidPage(
textInput("txt", "Enter your text here", "Empty"),
verbatimTextOutput("value")
)
server <- function(input, output)
{
output$value <- renderText({ input$text })
}
# create shiny app object
# using shinyApp
shinyApp(ui, server)
R
# import shiny package
library(shiny)
# define fluid page layout
ui <- fluidPage(
textInput(inputId = "Name", label = "Enter your name"),
textOutput("txt")
)
server <- function(input, output, session)
{
output$txt <- renderText({
Name <- paste(input$Name, collapse = ", ")
paste("Welcome! to geeksforgeeks ", Name)
})
}
# create shiny app object
# using shinyApp
shinyApp(ui = ui, server = server)
R
# import shiny package
library(shiny)
# define fluid page layout
ui <- fluidPage(
sliderInput(inputId = "num",
label = "Choose a number",
value = 25, min = 1, max = 100),
# define plot inside
# a wellPanel
wellPanel(plotOutput("hist"))
)
server <- function(input, output)
{
output$hist <- renderPlot({
hist(rnorm(input$num), main = input$title)
})
}
# create shiny app object
# using shinyApp
shinyApp(ui = ui, server = server)
输出:
- shinyApp():它从显式 UI/服务器对或绕过包含 Shiny 应用程序的目录路径创建 Shiny 应用程序对象。
Syntax:
shinyApp(ui, server, onStart = NULL, options = list(), uiPattern = “/”, enableBookmarking = NULL)
shinyAppDir(appDir, options = list())
shinyAppFile(appFile, options = list())
Parameter | Description |
---|---|
ui | The UI definition of the app. |
server | It has three parameters: input, output, and session. It is called once for each session to ensure that each app is independent. |
onStart | A function that will be called before the app is actually run. |
options | Options that should be passed to the runApp. |
uipattern | A regular expression that will be applied to each GET request to determine whether the ui should be used to handle the request. |
enableBookmarking | Can be “url”, “server”, or “disable”.The default value is NULL. |
appDir | Path to directory that contains a Shiny app. |
appFile | Path to a .R file containing a Shiny application. |
例子:
R
# import shiny package
library(shiny)
# define fluid page layout
ui <- fluidPage(
sliderInput(inputId = "num",
label = "Choose a number",
value = 10, min = 1, max = 1000),
plotOutput("hist")
)
server <- function(input, output)
{
output$hist <- renderPlot({
hist(rnorm(input$num))
})
}
# create shiny app object
# using shinyApp
shinyApp(ui = ui, server = server)
输出:
- reactive():它创建一个反应式表达式。反应式表达式是其结果将随时间变化的表达式。reactive() 包装一个普通表达式以创建一个反应式表达式。
Syntax: reactive(x, env = parent.frame(), quoted = FALSE, label = NULL)
Parameter | Description |
---|---|
x | An expression. |
env | The parent environment for reactive expression. |
quoted | Is the expression quoted? By default, this is FALSE. This is useful when you want to use an expression that is stored in a variable |
label | A label for reactive expression. |
例子:
R
# import shiny package
library(shiny)
# define fluid page layout
ui <- fluidPage(
textInput(inputId = "num", label = "Choose a number",
value = "", width = 100, placeholder = NULL),
plotOutput("hist"),
verbatimTextOutput("stats")
)
server <- function(input, output)
{
# use reactive to create
# a reactive expression
data <- reactive({rnorm(input$num)})
output$hist <- renderPlot({hist(data())})
output$stats <- renderPrint({summary(data())})
}
# create shiny app object
# using shinyApp
shinyApp(ui = ui, server = server)
输出:
现在,将输入值从 50 更改为 100,看看会发生什么。
输出值(直方图和摘要)也随着输入值的变化而变化,即应用程序具有反应性。
- observeEvent():它触发代码在服务器上运行。响应“类似事件”的响应式输入、值和表达式。
Syntax:
observeEvent(eventExpr, handlerExpr, event.env = parent.frame(), event.quoted = FALSE, handler.env = parent.frame(), handler.quoted = FALSE, label = NULL, suspended = FALSE, priority = 0, domain = getDefaultReactiveDomain(), autoDestroy = TRUE, ignoreNULL = TRUE, ignoreInit = FALSE, once = FALSE)
Parameter | Description |
---|---|
eventExpr | A expression that represents the event.It can be a simple or a complex reactive expression. |
handler.Expr | The expression to call whenever eventExpr is invalidated. |
event.env | The parent environment for eventExpr. By default, this is the calling environment. |
event.quoted | Returns whether the eventExpr expression is quoted or not. By default, this is FALSE. |
handler.env | The parent environment for handlerExpr. By default, this is the calling environment. |
handler.quoted | Returns whether the handlerExpr expression is quoted or not. By default, this is FALSE. |
label | A label for the observer or reactive |
suspended | If TRUE, start the observer in a suspended state. |
priority | An integer or numeric that controls the priority with which this observer should be executed.Positive,Negative and Zero values are allowed. |
autodestroy | If TRUE (the default), the observer will be automatically destroyed when its domain (if any) ends. |
ignoreNULL | Whether the action should be triggered when the input is NULL. |
ignoreInit | If TRUE, then, when this observeEvent is first created/initialized, ignore the handlerExpr (the second argument), whether it is otherwise supposed to run or not. The default is FALSE. |
once | Whether this observeEvent should be immediately destroyed after the first time that the code in handlerExpr is run. |
例子:
R
# import shiny package
library(shiny)
# define fluid page layout
ui = fluidPage(
textInput(inputId = "num",
label = "Enter a numeric value", value = "10"),
actionButton("button", "Calculate"),
column(8, tableOutput("table"))
)
server = function(input, output)
{
# Take an action every time button is pressed
observeEvent(input$button, {
cat("Showing", input$num, "rows\n")
})
# Take a reactive dependency
# on input$num, but not on any
# of the stuff inside the function
df <- eventReactive(input$button, {
head(cars, input$num)
})
output$table <- renderTable({
df()
})
}
# create shiny app object
# using shinyApp
shinyApp(ui, server)
输出:
- eventReactive():仅响应特定值的反应式表达式。响应“类似事件”的响应式输入、值和表达式。
Syntax:
eventReactive(eventExpr,
valueExpr,
event.env = parent.frame(),
event.quoted = FALSE,
value.env = parent.frame(),
value.quoted = FALSE,
label = NULL,
domain = getDefaultReactiveDomain(),
ignoreNULL = TRUE,
ignoreInit = FALSE)
Parameter | Description |
---|---|
eventExpr | An expression that represents the event.It can be a simple or a complex reactive expression. |
valueExpr | It produces the return value of the eventReactive. It will be executed within an isolate() scope. |
event.env | The parent environment for eventExpr. By default, this is the calling environment. |
event.quoted | Returns whether the eventExpr expression is quoted or not. By default, this is FALSE. |
value.env | The parent environment for valueExpr. By default, this is the calling environment. |
value.quoted | Returns whether the valueExpr expression is quoted or not. By default, this is FALSE. |
ignoreNULL | Whether the action should be triggered when the input is NULL. |
ignoreInit | If TRUE, then, when this observeEvent is first created/initialized, ignore the handlerExpr (the second argument), whether it is otherwise supposed to run or not. The default is FALSE. |
例子:
R
# import shiny package
library(shiny)
# define fluid page layout
ui <- fluidPage(
sliderInput(inputId = "num",
label = "Choose a number",
value = 25, min = 1, max = 100),
actionButton(inputId = "go",
label = "Update"),
plotOutput("hist")
)
server <- function(input, output)
{
data <- eventReactive(input$go, {
rnorm(input$num)
})
output$hist <- renderPlot({
hist(data())
})
}
# create shiny app object
# using shinyApp
shinyApp(ui = ui, server = server)
输出:
在这里,除非触发更新按钮,否则输出不会随输入值而变化
- actionButton():它创建一个动作按钮或一个链接。它们的初始值为零,每次按下时递增一。
Syntax:
actionButton(inputId, label, icon = NULL, width = NULL, …)
actionLink(inputId, label, icon = NULL, …)
Parameter | Description |
---|---|
inputId | The input slot that will be used to access the value. |
label | The contents of the button or link. |
icon | An optional icon() to appear on the button. |
width | The width of the input(ex-‘200px’,or’100%’). |
…. | Named attributes to be applied to the button or link. |
例子:
R
# import shiny package
library(shiny)
# define fluid page layout
ui <- fluidPage(
sliderInput("obs", "Number of observations", 0, 1000, 500),
actionButton("goButton", "Go!", class = "btn-success"),
plotOutput("distPlot")
)
server <- function(input, output)
{
output$distPlot <- renderPlot({
input$goButton
dist <- isolate(rnorm(input$obs))
hist(dist)
})
}
# create shiny app object
# using shinyApp
shinyApp(ui, server)
输出:
一旦单击actionButton(Go!) ,输出就会更新。
- checkboxGroupInput():它创建一组复选框,可用于独立切换多个选择。服务器将接收输入作为所选值的字符向量。
Syntax:
checkboxGroupInput(inputId, label, choices = NULL, selected = NULL, inline = FALSE, width = NULL, choiceNames = NULL, choiceValues = NULL)
Parameter | Description |
---|---|
inputId | The input slot that will be used to access the value. |
label | The contents of the button or link. |
choices | List of values to show checkboxes for. If elements of the list are named then that name rather than the value is displayed to the user. |
selected | The initial selection. |
inline | If TRUE, render the choices horizontally. |
width | The width of the input(ex-‘200px’,or’100%’). |
choiceValues, choiceNames | List of names and values. |
例子:
R
# import shiny package
library(shiny)
# define fluid page layout
ui <- fluidPage(
checkboxGroupInput("icons", "Choose icons:",
choiceNames =
list(icon("dog"), icon("cat"),
icon("fish"), icon("bug")),
choiceValues =
list("dog", "cat", "fish", "bug")),
textOutput("txt")
)
server <- function(input, output, session)
{
output$txt <- renderText({
icons <- paste(input$icons, collapse = ", ")
paste("You chose", icons)
})
}
# create shiny app object
# using shinyApp
shinyApp(ui = ui, server = server)
输出:
- textInput():它创建一个文本输入标签。
Syntax:
textInput(inputId, label, value = “”, width = NULL, placeholder = NULL)
Parameter | Description |
---|---|
inputId | The input slot that will be used to access the value. |
label | The contents of the button or link. |
value | The initial value. |
width | The width of the input(ex-‘200px’,or’100%’). |
placeholder | A character string giving the user a hint as to what can be entered into the control. |
例子:
R
# import shiny package
library(shiny)
# define fluid page layout
ui <- fluidPage(
textInput("txt", "Enter your text here", "Empty"),
verbatimTextOutput("value")
)
server <- function(input, output)
{
output$value <- renderText({ input$text })
}
# create shiny app object
# using shinyApp
shinyApp(ui, server)
输出:
- 文本输出(): 它创建一个文本输出元素。将反应式输出变量呈现为应用程序页面中的文本。
Syntax:
textOutput(outputId, container = if (inline) span else div, inline = FALSE)
Parameter | Description |
---|---|
outputId | The output variable to read the value from. |
container | A function to generate an HTML element to contain the text. |
inline | Use an inline (span()) or block container (div()) for the output. |
例子:
R
# import shiny package
library(shiny)
# define fluid page layout
ui <- fluidPage(
textInput(inputId = "Name", label = "Enter your name"),
textOutput("txt")
)
server <- function(input, output, session)
{
output$txt <- renderText({
Name <- paste(input$Name, collapse = ", ")
paste("Welcome! to geeksforgeeks ", Name)
})
}
# create shiny app object
# using shinyApp
shinyApp(ui = ui, server = server)
输出:
- 井面板(): 创建一个带有略微嵌入边框和灰色背景的面板。
Syntax: wellPanel(…)
Parameter | Description |
---|---|
… | UI elements to include inside the panel. |
例子:
R
# import shiny package
library(shiny)
# define fluid page layout
ui <- fluidPage(
sliderInput(inputId = "num",
label = "Choose a number",
value = 25, min = 1, max = 100),
# define plot inside
# a wellPanel
wellPanel(plotOutput("hist"))
)
server <- function(input, output)
{
output$hist <- renderPlot({
hist(rnorm(input$num), main = input$title)
})
}
# create shiny app object
# using shinyApp
shinyApp(ui = ui, server = server)
输出:
观察直方图位于灰色框(wellPanel)内。