1

我有一个基本的 R 代码,用户可以在代码中输入国家名称“阿根廷”。使用该值/名称,代码将对预加载数据的“阿根廷”子集运行分析。最后,代码将生成一个简单的 ggplot 显示结果。

我试图把这段代码变成一个闪亮的应用程序,但是我不能让它正常工作。我的主要问题是我似乎无法让服务器部分中的数据分析工作,这应该随后输入到绘图代码中。更重要的是,我似乎无法让用户输入的国家名称进入我的数据分析。

在不深入代码细节的情况下,有人可以指出我在 Shiny 中如何做到这一点的正确方向吗?例如

  1. 用户输入字段;

  2. 将该用户输入用作代码中使用的对象;

  3. 随后运行分析(无论它可能是什么);和

  4. 使用 ggplot 中的最终分析数据框,在闪亮的应用程序中显示图形输出。

请查看我当前使用的闪亮代码,以及使用 MTcars 的可重现数据

library(shiny)

# Some Sample data to run app using mtcars
mtcars$Primary<- rownames(mtcars)
mtcars$Area <- "Argentina"
mtcars$Y2016<- mtcars$mpg
mtcars$Element <- "Gross Production Value (constant 2004-2006 million US$)"

# Defining UI ----
ui <- pageWithSidebar(

          # App title ----
          headerPanel("Subsector Selection Tool"),

          # Sidebar panel for inputs ----
          sidebarPanel(

            # Input: Country name
            textInput("country", "Please enter country name", "")#,
          ),

          # Main panel for displaying outputs ----
          mainPanel("")
)


# Define server logic to plot various variables against mpg ----
server <- function(input, output) {

 #Trying to make user inputed country name into an object to be used in 
 "reactive" code below, which in turn is be used to make dataset for graphing
 country_interest <- reactive({
 paste(input$country)
 })


#Here I am trying to make the data analysis code run and create desired 
dataset for graphing, and subsetting for country selected by user
Value_c_e_PRIM_x  <- reactive({

Value_c <- Value[which(Value$Area==country_interest),]
Value_c_e <- Value_c[which(Value_c$Element=="Gross Production Value (constant 2004-2006 million US$)"),]
Value_c_e_PRIM$Primary <- Value_c_e_PRIM[,120]
Value_c_e_PRIM[,120] <- NULL

Value_c_e_PRIM <-  Value_c_e_PRIM %>% group_by(Primary,Element) %>% summarise_at(vars(Y2016), sum)

Value_c_e_PRIM$Category <- "Value of Production"
Value_c_e_PRIM$Value <- Value_c_e_PRIM$Y2016
Value_c_e_PRIM <-  Value_c_e_PRIM %>% group_by(Category,Primary) %>% summarise_at(vars(Value), mean)

})


#Graphing section, if  Ihave the dataset "Value_c_e_PRIM_x" pre-loaded (e.g. not derived in code above), the figure is successfully shown in the output.
output$plot <- renderPlot({

Graph_data <- Value_c_e_PRIM_x 
Graph_data$Score_type <- "Competitiveness Score"
Graph_data$`Competitiveness Score` <- round(Graph_data$Value, 2)

title1 <-paste("Competitiveness\nby",paste0(country_interest),"Subsector")
mycol <-c("red", "yellow", "#006600")

ggplot(data = Graph_data, aes(x = Score_type, y = reorder(Primary,Value), fill=Value)) +
  geom_tile(aes(fill = Value), colour= "white")+
  geom_text(data=Graph_data,aes(y=Primary, x= Score_type, label=Value))+
  labs(title =(paste0(title1)),y = "", x = "")+
  scale_fill_gradientn(colours = mycol)+
  theme(legend.title=element_blank())+
  theme(legend.position="bottom")

 })
}

shinyApp(ui, server)
4

0 回答 0