[英]How to fix a matrix value when running updateMatrixInput function in R shiny?
下面的簡單 MWE 代碼反映了對 (a) 周期 (X) 的滑塊輸入和 (b) X 變量(對於周期,鏈接到其上方的滑塊輸入)和 Y 變量的矩陣輸入的變化,在圖表中就在主面板中。 默認值,在開始時,X = 60 和 Y = 0.20。
工作正常,除了當矩陣輸入中的 Y 變量從默認值 0.20 更改時,隨后移動滑塊輸入會將 Y 變量重置回 0.20。 我將如何解決這個問題,以便 Y 變量保持靜態(保持更改后的值),而不是在移動輸入滑塊時恢復為默認值?
代碼:
library(shiny);library(shinyMatrix);
matrix2.input <- function(x,y,z){
matrixInput(
x,
value = matrix(c(y,z),1,2,dimnames=list(NULL,c("X","Y"))),
rows = list(extend = FALSE, names = FALSE),
cols = list(extend = FALSE, names = TRUE, editableNames = FALSE),
class = "numeric")}
matrix.validate <- function(x,y){
a <- x
a[,1][a[,1]>y] <- y
b <- diff(a[,1,drop=FALSE])
b[b<=0] <- NA
b <- c(1,b)
a <- cbind(a,b)
a <- na.omit(a)
a <- a[,-c(3),drop=FALSE]
return(a)}
vector <- function(X,Y,Z){
a <- rep(NA, X)
a[Y] <- Z
a[seq_len(min(Y)-1)] <- a[min(Y)]
if(max(Y) < X){a[seq(max(Y)+1, X, 1)] <- 0}
a <- approx(seq_along(a)[!is.na(a)],a[!is.na(a)],seq_along(a))$y
b <- seq(1:X)
c <- data.frame(X = b, Z = a)
return(c)}
vector.final <- function(x,y){vector(x,matrix.validate(y,x)[,1],matrix.validate(y,x)[,2])}
ui <-
pageWithSidebar(
headerPanel("Model"),
sidebarPanel(
sliderInput("periods","Nbr periods (X):",min=1,max=120,value=60),
matrix2.input("vector_input",60,.2)
), # close sidebar panel
mainPanel(plotOutput("graph1"))
) # close page with sidebar
server <- function(input,output,session)({
periods <- reactive(input$periods)
vector_input <- reactive(input$vector_input)
observeEvent(input$periods,{
updateMatrixInput(session,"vector_input",
value=matrix(c(input$periods,0.2),1,2,
dimnames=list(NULL, c("X","Y")))
) # close update matrix
}) # close observe event
output$graph1 <- renderPlot({plot({vector.final(periods(),vector_input())})})
}) # close server
shinyApp(ui, server)
在上面代碼的Server
部分的observeEvent
中嵌入的updateMatrixInput
函數中嵌入的matrix
函數中(好吧,從底部開始的第 7 行代碼),將 0.2 的值替換為input$vector_input[,2]
。 這為我清除了錯誤。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.