我很擅长使用Shiny,并且在将反应值添加到现有数据框时遇到一些问题。
我想使用一些预先存在的数据绘制带有回归线的散点图,并使用用户点击进行更新。我找到了一个有用的示例,但我无法弄清楚如何在数据框中存储反应值以更新回归线。
这是我尝试过的。谢谢。
library(shiny)
ui <- basicPage(
plotOutput("plot1", click = "plot_click"),
verbatimTextOutput("info"),
actionButton("updateplot", "Update Plot:"),
actionButton("refreshlinie", "Rlinie"),
)
server <- function(input, output) {
var1 <- c(3, 10, 15, 3, 4, 7, 1, 12, 8, 18, 20, 4, 4, 5, 10)
var2 <- c(4, 10, 12, 17, 15, 20, 14, 3, 4, 15, 12, 5, 5, 6, 2)
df <- cbind (var1, var2)
val <- reactiveValues(clickx = NULL, clicky = NULL, data = NULL)
observe({
input$plot_click
isolate({
val$clickx = c(val$clickx, input$plot_click$x)
val$clicky = c(val$clicky, input$plot_click$y)
})
# isolate({
# val$data = rbind(df, c(val$clickx, val$clicky))
#})
}) #adding clicks to list
output$plot1 <- renderPlot({
plot(val$data[,1], val$data[,2])
input$updateplot
isolate({
points(val$clickx, val$clicky)
})
if(input$refreshlinie)
abline(lm(val$data[,1]~ val$data[,2]))
})
output$info <- renderText({
paste0("x = ", val$clickx, ", y = ",val$clicky, "\n")
})
}
shinyApp(ui, server)
答案 0 :(得分:1)
基本思想是使用预先存在的数据初始化无功值。延迟添加新点的反应值。
Bellow我提供了一个简化版的代码,用于更新vla$data
中的点并正确更新abline
。
ui <- basicPage(
plotOutput("plot1", click = "plot_click"),
actionButton("updateplot", "Update Plot:"),
actionButton("refreshlinie", "Rlinie"),
verbatimTextOutput("info")
)
server <- function(input, output) {
var1 <- c(3, 10, 15, 3, 4, 7, 1, 12, 8, 18, 20, 4, 4, 5, 10)
var2 <- c(4, 10, 12, 17, 15, 20, 14, 3, 4, 15, 12, 5, 5, 6, 2)
n <- length(var1)
# initialize reactive values with existing data
val <- reactiveValues( clickx = NULL, clicky = NULL, data = cbind (var1, var2))
observe({
input$plot_click
isolate({
# save new points added
val$clickx = c(val$clickx, input$plot_click$x)
val$clicky = c(val$clicky, input$plot_click$y)
# add new points to data
val$data <- rbind(val$data, cbind(input$plot_click$x, input$plot_click$y))
})
})
output$plot1 <- renderPlot({
input$updateplot
plot(val$data[,1], val$data[,2])
if(input$refreshlinie)
# I changed the order of the variables to create the model.
abline(lm(val$data[,2]~ val$data[,1]))
})
output$info <- renderText({
input$plot_click
paste0("x = ", val$clickx, ", y = ",val$clicky, "\n")
})
}
shinyApp(ui, server)