shiny:构建第一个应用

shiny:构建第一个应用

这本书的代码和数据集下载地址为:Web-Application-Development-with-R-Using-Shiny.zip。电子书我也找不到了。。。

最小的例子

ui.R 文件是对Shiny应用的UI的描述,经常是应用中最短最简单的代码。
server.R文件负责根据ui.R文件输入的参数进行计算,然后输出结果至ui.R展示。

为了让程序正确运行,你需要:

  1. 将这两个文件放在同一个文件夹里;
  2. 将工作目录切换至该文件夹;
  3. 加载shiny包;
  4. 在控制台运行runApp()。

ui.R代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
library(shiny)
shinyUI(pageWithSidebar(
headerPanel(
h1("最小的示例!")),
sidebarPanel(
textInput(inputId = "comment",
label = "说点什么吧!",
value = "初始值")
),
mainPanel(
h3("这些就是你说的:"),
textOutput("textDisplay")
)
))

server.R代码:

1
2
3
4
5
6
library(shiny)
shinyServer(function(input, output){
output$textDisplay <- renderText({
paste0("你说“", input$comment, "”。这里共有", nchar(input$comment), "个字。")
})
})

代码解释:

  1. inputId:这个参数对变量进行命名,这样就可以据此在server.R文件中被调用了;
  2. label:这个参数用来指示该输入什么;
  3. value:为输入框设置初始值。

效果:

运行runGist(6571951)可以查看所有可用的输入方法及其数据类型。

这个页面的实现代码如下:

  1. ui.R:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    library(shiny)
    fluidPage(
    titlePanel("shiny输入方法与数据类型"),
    sidebarLayout(
    sidebarPanel(
    # 多选框
    checkboxGroupInput(
    inputId = "checkGroup",
    label = "1. checkboxGroupInput",
    choices = list(
    "冰激凌" = "冰激凌",
    "雪糕" = "雪糕",
    "可乐" = "可乐"
    )
    ),

    # 勾选框
    checkboxInput(
    inputId = "boxInput",
    label = "2. checkboxInput"
    ),

    # 日期输入框
    dateInput(
    inputId = "theDate",
    label = "3. dateInput"
    ),

    # 日期范围输入
    dateRangeInput(
    inputId = "dateRange",
    label = "4. dateRangeInput"
    ),

    # 数值输入
    numericInput(
    inputId = "pickNumber",
    label = "5. numericInput",
    min = 1,
    max = 10,
    value = 1
    ),

    # 单选框
    radioButtons(
    inputId = "pickRadio",
    label = "6. radioButtons",
    choices = list(
    "出租车" = "出租车",
    "步行" = "步行"
    )
    ),

    # 下拉列表选项框
    selectInput(
    inputId = "comboBox",
    label = "7. selectInput",
    choices = list(
    "News" = "A",
    "Situation comedy" = "Sitcom",
    "Film" = "Film"
    )
    ),

    ## 滑条
    sliderInput(
    inputId = "slider",
    label = "8. sliderInput",
    min = 1,
    max = 8,
    value = 7,
    step = 1
    ),

    ## 文本输入框
    textInput(
    inputId = "comment",
    label = "9. textInput",
    value = "初始文本"
    )
    ),

    mainPanel(
    h3("输出与数据类型"),
    tableOutput("textDisplay")
    )
    )
    )
  2. server.R:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    library(shiny)
    function(input, output){
    output$textDisplay <- renderTable({
    getMat = matrix(
    c(
    paste(input$checkGroup, collapse = ","),
    class(input$checkGroup),
    input$boxInput,
    class(input$boxInput),
    as.character(as.Date(input$theDate, origin = "1970-01-01")),
    class(input$theDate),
    paste(as.character(as.Date(input$dateRange[[1]], origin = "1970-01-01")), as.character(as.Date(input$dateRange[[2]], origin = "1970-01-01")), collapse = ","),
    class(input$dateRange),
    input$pickNumber, class(input$pickNumber),
    input$pickRadio, class(input$pickRadio),
    input$comboBox, class(input$comboBox),
    input$slider, class(input$slider),
    input$comment, class(input$comment)
    ), ncol = 2, byrow = T
    )

    colnames(getMat) = c("Value", "Class")
    getMat
    })
    }

练习

下面的示例是我自己的练习,为了编写一个直方图的应用:

代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# ui
library(shiny)
shinyUI(
pageWithSidebar(
titlePanel("直方图示例"),
sidebarPanel(
textInput(
inputId = "title",
label = "图表标题:",
value = "直方图示例"
),
sliderInput(inputId = "length",
label = "随机序列的长度:",
value = 500,
min = 100,
max = 800,
step = 1)
),
mainPanel(
h3("图表"),
plotOutput("plotDisplay"))
)
)

# server
shinyServer(
function(input, output){
output$plotDisplay <- renderPlot(
hist(rnorm(input$length),
main = input$title,
family = "STSong")
)
}
)

谷歌分析应用

这个应用是这个样子的:

1
runGitHub("ChrisBeeley/GoogleAnalyticsAdvanced")

UI

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
library(shiny)
packageCheck = unlist(packageVersion("shiny"))
if(packageCheck[1] == 0 & packageCheck[2] < 9){
shinyOld <- TRUE
} else {
shinyOld <- FALSE
}
shinyUI(pageWithSidebar(
headerPanel("谷歌分析"),
sidebarPanel(
conditionalPanel(
condition = "input.theTabs != 'hourly'",
dateRangeInput(inputId = "dateRange",
label = "日期范围",
start = "2013-01-01",
end = Sys.Date(),
max = Sys.Date())
),
checkboxInput(inputId = "smoother",
label = "是否添加平滑器?",
value = F),
conditionalPanel(
condition = "input.smoother == true",
selectInput("linearModel", "线性或者平滑模型",
list("lm", "loess"))
),

conditionalPanel(
condition = "input.theTabs != 'monthly'",
sliderInput(inputId = "minimumTime",
label = "最短时间(小时)",
min = 0,
max = 23,
value = 0,
step = 1),
sliderInput(inputId = "maximunTime",
label = "最长时间(小时)",
min = 0,
max = 23,
value = 23,
step = 1)
),
checkboxGroupInput(inputId = "domainShow",
label = "是否显示NHS和其它域名",
choices = list(
"NHS users" = "NHS",
"Other" = "Other"
),
selected = c(
ifelse(shinyOld, "NHS users", "NHS"),
"Other"
)
),
radioButtons(inputId= "outputType",
label = "输出类型",
choices = list(
"Visitors" = "visitors",
"Bounce rate" = "bounceRate",
"Time on site" = "timeOnSite"
)),
sliderInput(inputId = "animation",
label = "随时间变化的趋势",
min = 0,
max = 80,
value = 0,
step = 5,
animate = animationOptions(interval = 1000,
loop = F)),
# 一种下拉列表框
uiOutput("reacDomains")
),
mainPanel(
tabsetPanel(id = "theTabs",
tabPanel("总结",
h2(textOutput("textDisplay")),
value = "summary"),
tabPanel("月度图表",
plotOutput("monthGraph"),
downloadButton("downloadData.trend",
"下载图表"),
value = "monthly"),
tabPanel("小时图表",
plotOutput("hourGraph"),
value = "hourly"),
tabPanel("动态趋势",
plotOutput("animateGraph"),
value = "animTab")
)
)
))

Server

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
library(shiny)
library(plyr)
library(ggplot2)
# download.file("https://github.com/ChrisBeeley/GoogleAnalyticsAdvanced/raw/master/analytics.Rdata", "analytics.Rdata")
# 这是一个网站访问量的数据
load("analytics.Rdata")
library(ggpomological)
theme_set(theme_pomological(
base_family = "MLingWaiMedium-SC",
base_size = 25))
packageCheck = unlist(packageVersion("shiny"))
if(packageCheck[1] == 0 & packageCheck[2] < 9){
shinyOld <- TRUE
} else {
shinyOld <- FALSE
}

shinyServer(function(input, output, session){
# 如果"是否显示NHS和其它域名"的两个选项都没选就自动选择NHS users
observe({
if(class(input$domainShow) != "character"){
updateCheckboxGroupInput(session,
"domainShow",
choices = list(
"NHS users" = "NHS",
"Other" = "Other"
),
selected = ifelse(
shinyOld, "NHS users", "NHS"
))
}
})
# 获取网址列表
output$reacDomains <- renderUI({
domainList = unique(as.character(
passData()$networkDomain
))
selectInput("subDomains", "选择子域名", domainList)
})

# 这一段没看懂是干嘛的,删掉似乎也不影响
observe({
searchString <- parseQueryString(session$clientData$url_search)
if(length(searchString) > 0){
if(searchString[[1]] == "nhs"){
updateCheckboxGroupInput(
session,
"domainShow",
choices = list(
"NHS users" = "NHS",
"Other" = "Other"
),
selected = "NHS"
)
updateRadioButtons(session, "outputType",
choices = list(
"Visitors" = "visitors",
"Bounce rate" = "bounceRate",
"Time on site" = "timeOnSite"
),
selected = "Bounce rate")
updateTabsetPanel(session,
inputId = "theTabs",
selected = "summary"
)
}
if(searchString[[1]] == "other"){
updateCheckboxGroupInput(session,
"domainShow",
choices = list(
"NHS users" = "NHS",
"Others" = "Other"
),
selected = c(
"NHS users",
"Other"
))
updateRadioButtons(session, "outputType",
choices = list(
"Visitors" = "visitors",
"Bounce rate" = "bouncerate",
"Time on site" = "timeOnSite"
),
selected = "Visitors")
updateTabsetPanel(session, inputId = "smoother",
value = T)
}
}
})
passData <- reactive({
if(input$theTabs != "hourly"){
analytics <- analytics[analytics$Date %in% seq.Date(input$dateRange[1], input$dateRange[2], by = "days"),]
}
if(input$theTabs != "monthly"){
analytics <-analytics[analytics$Hour %in% as.numeric(input$minimumTime):as.numeric(input$maximunTime),]
}
analytics <- analytics[analytics$Domain %in% unlist(input$domainShow),]
analytics
})

output$monthGraph <- renderPlot({
graphData <- ddply(passData(), .(Domain, Date), numcolwise(sum))
if(input$outputType == "visitors"){
theGraph <- ggplot(graphData, aes(Date, visitors, group = Domain, colour = Domain)) + geom_line() + ylab("Unique visitors") + scale_color_pomological()
}
if(input$outputType == "bounceRate"){
theGraph <- ggplot(graphData, aes(Date,
bounces/visits * 100,
group = Domain,
colour = Domain)) +
geom_line() + ylab("Bounce rate %")
}
if(input$outputType == "timeOnSite"){
theGraph <- ggplot(graphData, aes(x = Date,
y = timeOnSite/visits,
group = Domain,
colour = Domain)) +
geom_line() + ylab("Average time on site")
}
if(input$smoother){
theGraph <- theGraph +
geom_smooth(method = input$linearModel)
}
print(theGraph)
})
output$animateGraph <- renderPlot({
graphData <- ddply(passData(), .(Domain, Date), numcolwise(sum))
if(input$outputType == "visitors"){
theGraph <- ggplot(graphData, aes(x = Date,
y = visitors,
group = Domain,
colour = Domain)) +
geom_line() + ylab("Unique visitors") + scale_color_pomological()
}
if(input$outputType == "bounceRate"){
theGraph <- ggplot(graphData, aes(x = Date,
y = bounces/visits * 100,
group = Domain,
colour = Domain)) +
geom_line() + ylab("Bounce rate %") + scale_color_pomological()
}

if(input$outputType == "timeOnSite"){
theGraph <- ggplot(graphData,
aes(x = Date,
y = timeOnSite/visits * 100,
group = Domain,
colour = Domain)) +
geom_line() + ylab("Average time on site") + scale_color_pomological()
}
smoothData = graphData[graphData$Date %in%
quantile(graphData$Date, input$animation/100, type = 1):
quantile(graphData$Date, (input$animation+20)/100, type = 1),]
theGraph <- theGraph + geom_smooth(data = smoothData, method = "lm", colour = "black")
print(theGraph)
})
output$hourGraph <- renderPlot({
graphData = ddply(passData(), .(Domain, Hour), numcolwise(sum))
if(input$outputType == "visitors"){
theGraph <- ggplot(graphData,
aes(x = Hour,
y = visitors,
group = Domain,
colour = Domain)) +
geom_line() +
ylab("Unique visitors") + scale_color_pomological()
}
if(input$outputType == "bounceRate"){
theGraph <- ggplot(graphData,
aes(x = Hour,
y = bounces/visits,
group = Domain,
colour = Domain)) +
geom_line() + ylab("Bounce rate %") + scale_color_pomological()
}
if(input$outputType == "timeOnSite"){
theGraph <- ggplot(graphData,
aes(x = Hour,
y = timeOnSite/visits,
group = Domain,
colour = Domain)) +
geom_line() + ylab("Average time on site") + scale_color_pomological()
}
if(input$smoother){
theGraph <- theGraph + geom_smooth(method = "loess")
}
print(theGraph)
})
output$textDisplay <- renderText({
if(is.null(input$dateRange)) return()
paste(
length(seq.Date(input$dateRange[1],
input$dateRange[2],
by = "days")),
" days are summarised. There were",
sum(passData()$visitors),
"visitors in this time period."
)
})
# 下面的代码用于定义下载图片
myTrend <- reactive({
graphData <- ddply(passData(), .(Domain, Date), numcolwise(sum))
if(input$outputType == "visitors"){
theGraph <- ggplot(graphData,
aes(x = Date,
y = visitors,
group = Domain,
colour = Domain)) +
geom_line() +
ylab("Unique visitors")
}
if(input$outputType == "bounceRate"){
theGraph <- ggplot(graphData,
aes(x = Date,
y = bounces/visits * 100,
group = Domain,
colour = Domain)) +
geom_line() + ylab("Bounce rate %") + scale_color_pomological()
}
if(input$outputType == "timeOnSite"){
theGraph <- ggplot(graphData,
aes(x = Date,
y = timeOnSite/visits,
group = Domain,
colour = Domain)) +
geom_line() + ylab("Average time on site") + scale_color_pomological()
}
if(input$smoother){
theGraph <- theGraph + geom_smooth(method = input$linearModel)
}
print(theGraph)
})
output$downloadData.trend <- downloadHandler(
filename = function(){
paste("Trend_plot", Sys.Date(), ".png", sep = "")
},
content = function(file){
png(file, width = 980, height = 400,
units = "px", pointsize = 12,
bg = "white", res = NA)
trend.plot <- myTrend()
print(trend.plot)
dev.off()
},
contentType = "image/png"
)
})

网页应用效果:

还有一个动图,比较大,加载会很慢:

# Shiny

评论

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×