【发布时间】:2019-10-18 16:30:20
【问题描述】:
我想从下拉列表中选择选项,这些选项作为不同的属性存储在我的数据框中,并使用滑块更改年份,以便我可以看到它对 valueCard 的影响。我被卡住的地方是,要找出如何从 df1 数据帧调用 pf_rol 属性以反映其在 valueCard 上的值。
我已经成功创建了 2 个值卡,它们可以通过一个滑块来操作,但现在我想使用滑块和 selectInput 来更改 ValueCard 'pfrol' 中的值。
PS:如果有人帮助绘制地图,我将不胜感激。我有所有国家/地区的名称,并希望通过滑块来操纵不同的属性,以观察变化的趋势,就像价值卡一样。
global.r
df <- read.csv("hfi_cc_2018.csv", header = T)
summary(df)
sapply(df, function(x) sum(is.na(x)))
#Replace Null Values
df[is.na(df)] <- 0
df[,5:ncol(df)] <- round(df[,5:ncol(df)], 2)
#adding selective columns new df1
#https://stackoverflow.com/questions/10085806/extracting-specific-columns-from-a-data-frame
df1<- df[, (names(df) %in% c("year","countries","region","pf_rol", "pf_ss_homicide","pf_ss_disappearances_violent",
))]
ui.r
require(shiny)
require(shinydashboard)
shinyUI(
dashboardPage(
dashboardHeader(title = "Human Freedom Index", titleWidth = 300),
dashboardSidebar(
sliderInput("years","Select Year:",
min = min(df1$year),
max = max(df1$year),
value = min(df1$year),
step = 1),
selectInput("variable","Select Freedom Factor:",
choices = list("Rule of Law"= "pf_rol",
"Homicides Reported" = "pf_ss_homicide")
)
),
dashboardBody(
fluidRow(
valueBoxOutput("pfrol"),
valueBoxOutput("pfrank"),
valueBoxOutput("efrank")
),
fluidRow(
box(plotlyOutput("plot1"), width=15, height=400)
)
)
)
)
服务器.r
require(shiny)
require(dplyr)
require(shinydashboard)
shinyServer(function(input,output){
observe({
(card <- df1 %>%
filter(year == input$years))
output$pfrank = renderValueBox(
valueBox(round(mean(card$pf_score),1),
"Personal Freedom Score")
)
})
observe({
if(input$variable == "Rule of Law"){
if(filter(df1$year == input$years)){
output$pfrol = renderValueBox(
valueBox(round(mean(df1$pf_rol),1),
"Rule of Law")
)
}
}
})
})
【问题讨论】:
-
了解观察和反应之间的区别。您的代码几乎包含了您在 Shiny 中可以做的所有不良做法
-
您能否解释一下我可以修改代码的哪些区域。我是 R 的新手,而且很闪亮。
-
stackoverflow.com/questions/53016404/… 这是一本好书 :-)
-
我建议将代码分解为您遇到的问题。看到所有这些代码并不能激励其他人回答这个问题。也许你可以缩短问题。例如:以下问题与您的问题
plot_ly(card, x = card$pf_score, y = card$ef_score, text = card$countries, type = 'scatter', color = card$region, colors = 'Paired', mode = 'markers',marker = list( size = 20, opacity = 0.4 )) %>% layout(title = 'Personal _Freedom vs Economical Freedom', xaxis = list(showgrid = FALSE), yaxis = list(showgrid = FALSE))是否真的相关? -
感谢您的提醒,现已编辑。请告诉我如何解决我的问题?
标签: r shiny shinydashboard selectinput