到目前为止,我有一个工作正常的复杂函数.我需要让非程序员在工作中使用这个功能,我开始创建一个简单的应用程序.

问题是,在我的用户定义函数中,我创建了一个作为对象存储的图形,以及作为数据帧存储的最终输出,然后返回.所有重要的结果都会在以后导出.所有这些都运行得很好. 但我希望我的最终图形绘制在Rshiny 的范围内.

我试图举出一个我仍在为之奋斗的小例子

    test_function <- function(x){
  new_data <- iris[iris$Species==x,] %>% droplevels()
  write.csv(new_data,"test.csv")
  new_plot <- plot(new_data$Sepal.Length,new_data$Petal.Length)
  new_plot %>% plot
  return(new_data)
} # I would run my code outside the app, I would see the plots in my Rstudio plot panel.

ui <- fluidPage(
  
  # Application title
  titlePanel("Test for 2022"),
  
  # Sidebar with a slider input for number of bins
  sidebarLayout(
    sidebarPanel(
      textInput("Species",
                "Insert species name"),
      actionButton(inputId = "input_action", label = "Run")
      
    ),
    
    mainPanel(
      plotOutput("plot")
      
    )
  )
)


server <- function(input, output) {
  observeEvent(input$input_action, {
    taxa <- input$Species
    test_function(taxa)
  
  
  output$plot <- renderPlot({
    plot(test_function(input$Species))})
  })
}

ShinyApp(UI,服务器)#但这里没有图形,代码运行,..一切如愿以偿地出口.我需要更改什么才能在我更改输入名称时获得新的绘图?

推荐答案

返回地块而不是数据框

如果您的函数返回一个曲线图,并且您只需对其调用renderPlot(),那么您的服务器逻辑就会更简单.

test_function <- function(x) {
    new_data <- iris[iris$Species == x, ] %>% droplevels()
    plot(new_data$Sepal.Length, new_data$Petal.Length)
}

这样,您的服务器就可以呈现该函数的输出.

server <- function(input, output) {
    observeEvent(input$input_action, {
        output$plot <- renderPlot(test_function(input$Species))
    })
}

我没有更改ui,所以我没有在这里包括它,只包括服务器逻辑和函数的返回值.但是,我建议更改它,因为它使服务器逻辑更简单,而且对用户来说也可能更容易.

Use a selectInput()

目前您需要observeEvent()和一个Run按钮,因为当应用程序加载时,您的文本框为空.然而,如果您使用selectInput(),即下拉框,您的逻辑会更简单,特别是如果它有缺省值的话.

ui <- fluidPage(
    sidebarLayout(
        sidebarPanel(
            selectInput("Species", label = "Select species", choices = unique(iris$Species), selected = unique(iris$Species[1])),
        ),
        mainPanel(
            plot输出("plot")
        )
    )
)

server <- function(input, output) {
    output$plot <- renderPlot(test_function(input$Species))
}

您的逻辑中不再需要observeEvent(),您的服务器代码实际上只有一行.此外,您的用户界面更干净,因为您不需要运行按钮,并且您不需要引入逻辑来处理用户在文本框中输入无效或恶意输入.

输出

With text box and run button

enter image description here

With drop down box

enter image description here

R相关问答推荐

如何将具有重复名称的收件箱合并到R中的另一列中,而结果不同?

使用scale_x_continuous复制ggplot 2中的离散x轴

查找图下的面积

如何计算R数据集中每个女性的子元素数量?

如何在R中合并和合并多个rabrame?

如何在编辑列时更新可编辑数据表,并使用该表在Shiny中执行连续计算

gganimate在使用shadow_mark选项时不保留所有过go 的标记

如何使用STAT_SUMMARY向ggplot2中的密度图添加垂直线

如何使用ggplot对堆叠条形图进行嵌套排序?

R中的哈密顿滤波

给定开始日期和月份(数字),如何根据R中的开始日期和月数创建日期列

如何在R中通过多个变量创建交叉表?

`夹心::vcovCL`不等于`AER::tobit`标准错误

将标识符赋给事件序列,避免错误观察

按组跨多列创建伪变量

快速合并R内的值

R-找出存在其他变量的各种大小的所有组合

在R中添加要打印的垂直线

创建两个变量组合的索引矩阵

如果y中存在x中的值,则将y行中的多个值复制到相应的x行中